我需要在select column
的存储过程中的temp
表中cursor
。
以下是我尝试的以下脚本:
尝试:
DELIMITER $$
CREATE PROCEDURE `sptest2`(IN nm VARCHAR(50),IN sub VARCHAR(50))
BEGIN
DECLARE dp char(50);
DECLARE colmn_list varchar(100);
SET @q = CONCAT('CREATE TEMPORARY TABLE IF NOT EXISTS tem AS
(SELECT DISTINCT ', nm ,' AS Col FROM table1)');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DECLARE cursor_n CURSOR for select col from tem;
注意:这给了我错误。因为在一些操作之后我们无法declare cursor
。我们需要在BEGIN
之后声明它。
那么解决方案是什么?
答案 0 :(得分:1)
所有声明必须放在程序开始时:
DELIMITER $$
CREATE PROCEDURE `sptest2`(IN nm VARCHAR(50),IN sub VARCHAR(50))
BEGIN
DECLARE dp char(50);
DECLARE colmn_list varchar(100);
DECLARE cursor_n CURSOR for select col from tem;
SET @q = CONCAT('CREATE TEMPORARY TABLE IF NOT EXISTS tem AS
(SELECT DISTINCT ', nm ,' AS Col FROM table1)');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
但是根据您的要求,使用子查询是更好的解决方案。
在尝试创建它之前可能是一个好主意drop table,因为它的函数将被调用多次。
DROP TEMPORARY TABLE IF EXISTS tem;