我想:
步骤#3的问题,我得到user_id = NULL而不是游标中的整数。
CREATE PROCEDURE user_demo_sp()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE current_user INT;
DECLARE cur CURSOR FOR SELECT user_id FROM users_temp; -- Cursor on temp table
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Create a table
DROP temporary table if exists `users_temp` ;
CREATE temporary table `users_temp` (
user_id INT(11) NOT NULL,
aggregation_column INT(11) NOT NULL
);
-- Fill table
INSERT INTO users_temp SELECT user_id from users where condition ="condition";
OPEN cur;
read_loop: LOOP
FETCH cur INTO current_user;
IF done THEN
LEAVE read_loop;
END IF;
select current_user; -- Return NULL
END LOOP;
CLOSE cur;
END;
答案 0 :(得分:2)
你需要在声明光标之前填充临时表(只使用嵌套的Begin ... END块):
CREATE PROCEDURE user_demo_sp()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE current_user INT;
temp table
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Create a table
DROP temporary table if exists `users_temp` ;
CREATE temporary table `users_temp` (
user_id INT(11) NOT NULL,
aggregation_column INT(11) NOT NULL
);
-- Fill table
INSERT INTO users_temp SELECT user_id from users where condition ="condition";
Begin
DECLARE cur CURSOR FOR SELECT user_id FROM users_temp; -- Cursor on
OPEN cur;
read_loop: LOOP
FETCH cur INTO current_user;
IF done THEN
LEAVE read_loop;
END IF;
select current_user; -- Return NULL
END LOOP;
CLOSE cur;
End;
END;
同样在这样的场景中,你实际上不需要临时表 可以在你用来填充temptale的选择上声明光标