我试图从DB2系统中的游标中的多个表中删除。但是终结符;
导致我的光标过早退出。目前,我无法确定另一种设置此查询以实现所需结果的方法。
我尝试了以下声明:
DECLARE C1 CURSOR FOR
DELETE FROM TABLE1 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE2 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE3 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE4 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE5 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE6 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
DELETE FROM TABLE7 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM;
然而,这并没有按预期运行,这意味着它不会循环游标,而是只运行一次。
这也无法运行:
--#SET TERMINATOR @
DECLARE C1 CURSOR FOR
SELECT * FROM TABLE1 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE2 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE3 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE4 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE5 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE6 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@
SELECT * FROM TABLE7 WHERE ACCOUNT_NUMBER = ACCOUNT_NUMBER_PARAM@;
OPEN C1@
在这里,我尝试更改游标终止符,以便它进一步向下并实际打开并运行游标,但是这会引发错误并且根本没有运行。
如何重写此语句以在游标中运行多个select语句?
答案 0 :(得分:1)
在OPEN C1之后,您需要循环存储在光标中的结果。
使用
OPEN C1
FETCH NEXT FROM C1 INTO @Variable1,@Variable2,....( as many as fields in the table )
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM C1 INTO @Variable1,@Variable2,....( as many as fields in the table )
END
CLOSE CURSOR
DEALLOCATE CURSOS
答案 1 :(得分:0)
为什么需要游标来删除数据?
这样做要好得多:
DELETE FROM table1 WHERE colname = (SELECT colname FROM table1 WHERE condition);
DELETE FROM table2 WHERE colname = (SELECT colname FROM table2 WHERE condition);
DELETE FROM table3 WHERE colname = (SELECT colname FROM table3 WHERE condition);
DELETE FROM table4 WHERE colname = (SELECT colname FROM table4 WHERE condition);
在存储过程中运行它应该没有问题。