如何在 SQL 中的过程中使用 select 语句

How to use select statement in procedure in SQL

为什么我的 SQL 会抛出类似 LEAVE 且没有匹配标签的错误:tableList

DELIMITER $$
DROP PROCEDURE IF EXISTS CountSignatures$$

CREATE PROCEDURE CountSignatures()
  BEGIN
     DECLARE done INT DEFAULT FALSE;
     DECLARE signatureCount INT;
     DECLARE tableName CHAR(100);
     DECLARE tableList CURSOR FOR Select table_name from information_schema.tables where table_schema="LogData" and table_name like "%FAULT_20150320%";
     DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
     OPEN tableList;
     tableListLoop: LOOP
       SET done = FALSE ;
       FETCH tableList INTO tableName;
       IF done THEN
         LEAVE tableListLoop;
       END IF;
       ***select signatureCount := signatureCount + count(distinct signature) from tableList;*** Line giving syntax error
     END LOOP;
     CLOSE tableList;
  END$$
DELIMITER;

我不确定它为什么会产生那个特定的错误,但这行不正确:

signatureCount = signatureCount + Select count (distinct signature) from tableList;

如果要更新变量,请尝试:

set signatureCount = (signatureCount +
                      (select count(distinct signature)
                       from tableList));

但是,您没有初始化变量,所以这只会产生 NULL

leave 标签:

This statement is used to exit the flow control construct that has the given label. If the label is for the outermost stored program block, LEAVE exits the program.

在你的代码中 tableList 是一个游标,你应该保留 tableListLoop 而不是 tableList,所以试试:

LEAVE tableListLoop;