【发布时间】:2016-02-04 14:40:42
【问题描述】:
问题在于 FETCH INTO(在循环中)没有将值放入变量中。我查看了MYSQL | SP | CURSOR - Fetch cursor into variable return null,但该表已被填充。
事务表如下所示:
CREATE TABLE `transactionentry` (
`transactionid` bigint(20) NOT NULL AUTO_INCREMENT,
...
PRIMARY KEY (`transactionid`),
...
) ENGINE=InnoDB AUTO_INCREMENT=651 DEFAULT CHARSET=utf8;
存储过程:
PROCEDURE `doTxnHouseKeeping`()
BEGIN
-- Loop invariant
DECLARE noEntries INTEGER DEFAULT FALSE;
-- Error codes
DECLARE code CHAR(5) DEFAULT '00000';
DECLARE msg TEXT;
-- Txn vars
DECLARE transactionId BIGINT(20);
DECLARE lastTransactionId BIGINT(20) DEFAULT 0;
-- testing
DECLARE counter INT(11) DEFAULT 0;
DEClARE txnEntryCur CURSOR FOR
SELECT
`transactionid`
FROM
`transactionentry`
LIMIT 1;
DECLARE CONTINUE HANDLER FOR
NOT FOUND SET noEntries = TRUE;
DECLARE EXIT HANDLER FOR
SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT;
SELECT CONCAT('Error fetching transaction entries code: ', code, ' message: ', msg);
END;
OPEN txnEntryCur;
mainLoop: LOOP
FETCH
txnEntryCur
INTO
transactionId;
IF noEntries THEN
LEAVE mainLoop;
END IF;
IF transactionId IS NOT NULL THEN
INSERT INTO debugTable (`bigintval`) VALUES (transactionId);
ELSE
INSERT INTO debugTable (`strval`) VALUES ('transactionId is NULL');
END IF;
SET counter = counter + 1;
END LOOP mainLoop;
CLOSE txnEntryCur;
SELECT CONCAT("Count: ", counter);
END
运行存储过程会返回这个结果:
+--------------------------+
|CONCAT("Count: ", counter)|
+--------------------------+
| Count: 1|
+--------------------------+
调试表中的结果是:
+------------+---------+-----------------------+
|iddebugTable|bigintval| strval|
+------------+---------+-----------------------+
| 1| NULL|"transactionId is NULL"|
+------------+---------+-----------------------+
这意味着该值没有被复制
运行 SQL 时(就像在存储过程中一样),它返回:
+-------------+
|transactionid|
+-------------+
| 591|
+-------------+
【问题讨论】: