[英]Insert deleted rows to new table in stored procedure
如何insert
在delete
语句中delete
的行insert
到DB2 SQL中存储过程中的新表中?
DB2允许以下语法返回已删除的行:
select * from old table (
delete from my_table where foo > 1
)
由于某些原因,您不能仅基于该语句返回的结果进行insert
。 但是,您可以将常用表表达式用作繁杂的解决方法 :
with deleted as (
select * from old table (delete from my_table where foo > 1)
)
select * from new table (insert into archive_table select * from deleted)
这有一个我不需要的多余的select语句,但至少它可以工作。 删除的行将插入到另一个表中。
但是,如何在存储过程中执行此操作?
存储过程不允许裸选择语句。 我想把它放在set
陈述中:
set my_var = (
with deleted as (
select * from old table (delete from my_table where foo > 1)
)
select * from new table (insert into archive_table select * from deleted)
);
但是,这失败了,因为在这样的语句中不允许使用公共表表达式。
有什么办法可以在存储过程中做到这一点?
(可以使用其他方法作为替代方法来完成任务。但是,我想确定是否可以通过这种方式进行操作。如果无法实现,则似乎是很愚蠢的限制。)
更新:我正在使用DB2 9.7 LUW。
如果发出select
,则必须以某种方式使用结果集,无论结果集是在过程中还是在其他应用程序中。 您可以在过程中运行虚拟循环,例如:
for t in (with deleted as (
select * from old table (delete from my_table where foo > 1)
)
select * from new table (insert into archive_table select * from deleted)
) loop
null;
end loop;
或使用显式游标:
declare c1 cursor for with deleted as (
select * from old table (delete from my_table where foo > 1)
)
select * from new table (insert into archive_table select * from deleted);
...
open c1;
close c1;
请注意,这些都不经过测试。
你为什么不翻转它呢? 您可以从SELECT中插入,也可以从DELETE中选择行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.