8

我从 MySQL 游标中获取值时遇到问题。

我创建了一个临时表,它只是另一个表的副本(原始表有一个变量名,它作为过程的参数传递,并且因为 MySQL 不支持变量表名,我必须创建一个副本 - 不能直接使用原件)。

临时表的创建很顺利,所有应该在其中的数据都在那里。然后我定义了一个游标来遍历我的临时表......但是当我尝试在while循环中从游标中获取时,我的变量没有填充来自“游标”表的数据......其中大多数只是NULL,只有最后 2 个内部似乎有正确的值。

这是我的代码块:

-- variables to be filled from the cursor
DECLARE id,rain,snow,hs,clouds,rain2,cape,status,done int;
DECLARE v_v,v_u double;

-- cursor declaration
DECLARE iter CURSOR FOR (SELECT id,cape,rain,snow,hstones,clouds,raining,wind_u,wind_v FROM temp_tbl);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- drop the old temporary table if any
DROP TABLE IF EXISTS temp_tbl;

-- a statement to create the temporary table from a table with the specified name
-- (table_name is a parameter of the stored procedure this chunk is from)

SET @temp_table = CONCAT('CREATE TABLE temp_tbl AS SELECT * FROM ', table_name, ' WHERE 1'); 

-- prepare, execute and deallocate the statement
PREPARE ctmp FROM @temp_table;
EXECUTE ctmp;
DEALLOCATE PREPARE ctmp;

-- now the temp_table exists, open the cursor
OPEN iter;

WHILE NOT done DO

        -- fetch the values
        FETCH iter INTO id,cape,rain,snow,hs,clouds,rain2,v_u,v_v;

        -- fetch doesnt work, only v_u and v_v variables are fetched correctly, others are null

        -- ... further statements go here

END WHILE;

CLOSE iter;

FETCH 语句中是否有任何类型检查可能导致此类问题?我的临时表中的列(从原始表派生)只是小整数或小整数,所以这些应该与我在 fetch 语句中使用的整数完全兼容。最后两个是双打,但奇怪的是只有这两个双打被取出。甚至没有获取作为主键的 ID int 列。

我使用 dbForge Studio 进入并调试我的程序,但这不应该是问题。

4

1 回答 1

16

MySQL函数中,当参数名或变量名与字段名冲突时,使用参数名或变量名。

在这些声明中:

DECLARE id,rain,snow,hs,clouds,rain2,cape,status,done int;

DECLARE iter CURSOR FOR (SELECT id,cape,rain,snow,hstones,clouds,raining,wind_u,wind_v FROM temp_tbl);

您选择未初始化的变量,而不是字段。这和这样做是一样的:

DECLARE iter CURSOR FOR (SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, wind_u,wind_v FROM temp_tbl);

最后两个字段名不冲突,选择正确。

在变量名前加上下划线:

DECLARE _id, _rain, _snow, _hs, _clouds, _rain2, _cape, _status, _done INT;
于 2010-02-25T15:17:12.750 回答