How can I insert the rows deleted in a delete statement into a new table within a stored procedure in DB2 SQL?
DB2 allows the following syntax to return the deleted rows:
select * from old table (
delete from my_table where foo > 1
)
For some reason, you can't just do an insert based on the results returned from that statement. 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)
This has an unnecessary extra select statement that I don't want, but at least it works. Deleted rows get inserted into another table.
However, how can I do this within a stored procedure?
A stored procedure doesn't allow a bare select statement. I thought of putting it within a set statement:
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)
);
However, this fails because a common table expression is not allowed within such a statement.
Is there any way to do this within a stored procedure?
(The task can be done using some other method as a work-around. But I want to find out if it is possible to do it this way. If this is not possible, it seems like quite a dumb restriction.)
Update: I'm using DB2 9.7 LUW.