我需要根据我所处的情况在存储过程中动态创建游标,理想情况如下:
IF (varOrgGroupCode = '') THEN
BEGIN
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS`;
END;
ELSE
BEGIN
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS` WHERE `groupcode` = varOrgGroupCode;
END;
END IF;
上面的代码会导致语法错误。我用谷歌搜索了有人用临时表做了。谁能告诉我怎么样?
答案 0 :(得分:6)
您在Google上发现的事情可能是创建一个临时表,根据您的谓词填充该临时表,然后在游标声明中引用临时表。
这样的事情:
DELIMITER $$
CREATE PROCEDURE `some_procedure`(IN varOrgGroupCode varchar(100))
BEGIN
DECLARE bNoMoreRows BOOLEAN DEFAULT FALSE;
DECLARE vGroupCode varchar(100);
DECLARE groupCode CURSOR FOR
SELECT `groupcode` FROM `LICENSEKEYS_TEMP`;
declare continue handler for not found set bNoMoreRows := true;
BEGIN
drop table if exists LICENSEKEYS_TEMP;
create temporary table `LICENSEKEYS_TEMP` (groupCode varchar(100));
IF (varOrgGroupCode = '') THEN
insert into `LICENSEKEYS_TEMP` (groupCode) SELECT `groupcode` FROM `LICENSEKEYS`;
ELSE
insert into `LICENSEKEYS_TEMP` (groupCode) SELECT `groupcode` FROM `LICENSEKEYS` WHERE `groupcode` = varOrgGroupCode;
END IF;
open groupCode;
GROUPCODE_LOOP: loop
fetch groupCode into vGroupCode;
-- Do some stuff
if bNoMoreRows then
close groupCode;
leave GROUPCODE_LOOP;
end if;
END LOOP GROUPCODE_LOOP;
END;
END$$
DELIMITER ;