如何将insert
语句中删除的行delete
转换为DB2 SQL中存储过程中的新表?
DB2允许以下语法返回已删除的行:
select * from old table (
delete from my_table where foo > 1
)
出于某种原因,您不能仅根据该语句返回的结果执行insert
。 However, you can use common table expressions as a kludgy workaround:
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)
这有一个我不想要的不必要的额外选择语句,但至少它有效。已删除的行将插入另一个表中。
但是,如何在存储过程中执行此操作?
存储过程不允许使用裸选择语句。我想把它放在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。
答案 0 :(得分:1)
如果发出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;
请注意,这些都未经过测试。
答案 1 :(得分:0)
为什么不翻转它?您可以从SELECT中插入,也可以从DELETE中选择行。