【问题标题】:Insert deleted rows to new table in stored procedure在存储过程中将删除的行插入新表
【发布时间】:2013-08-16 09:46:36
【问题描述】:

如何将insertdelete 语句中删除的行放入 DB2 SQL 存储过程中的新表中?

DB2 允许以下语法返回已删除的行:

select * from old table (
    delete from my_table where foo > 1
)

出于某种原因,您不能只根据该语句返回的结果执行insertHowever, 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)

这有一个我不想要的不必要的额外选择语句,但至少它有效。删除的行被插入到另一个表中。

但是,如何在存储过程中做到这一点?

存储过程不允许使用简单的 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。

【问题讨论】:

    标签: sql stored-procedures db2


    【解决方案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;
    

    请注意,这些都没有经过测试。

    【讨论】:

    • 第一个选项不起作用(循环语句中不允许公共表表达式)。然而,第二个成功了。谢谢!
    【解决方案2】:

    你为什么不把它翻过来呢?您可以从 SELECT 中插入,也可以从 DELETE 中选择行。

    【讨论】:

    • 似乎有一个限制阻止您使用数据更改语句 {select from final table (delete...)} 作为插入行的源。
    • 对不起,如果我的问题不清楚。当我说“你不能只根据返回的结果进行插入”时,我的意思是 DB2 任意阻止你这样做。是的,如果可能的话,这样做是有意义的。不过,感谢您花时间回答。
    • 抱歉,早上喝杯咖啡前会教我回答:o/
    猜你喜欢
    • 2014-06-23
    • 1970-01-01
    • 2014-02-12
    • 2013-12-19
    • 2014-07-09
    • 1970-01-01
    • 2013-11-07
    • 2011-03-03
    相关资源
    最近更新 更多