gpt4 book ai didi

MySql 获取游标到变量返回空

转载 作者:行者123 更新时间:2023-11-29 03:55:57 24 4
gpt4 key购买 nike

问题在于 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|
+-------------+

最佳答案

我发现了问题,它很奇怪。它不会导致任何错误和/或异常,只是不会将任何值放入变量中。解决方案是将游标声明语句从:

DECLARE txnEntryCur CURSOR FOR 
SELECT
`transactionid`
FROM
`transactionentry`
LIMIT 1;

收件人:

DECLARE txnEntryCur CURSOR FOR 
SELECT
`transactionentry`.`transactionid`
FROM
`transactionentry`
LIMIT 1;

甚至文档也没有表明它可能是个问题 (https://dev.mysql.com/doc/refman/5.7/en/declare-cursor.html)

如果我从多个表中进行选择,我只会完全限定 SQL 语句的 SELECT(和 WHERE)部分,因此不会在更复杂的查询中选择它。

我希望这会在将来为某人节省一些时间。

关于MySql 获取游标到变量返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35203943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com