DB2 storing results from final table clause

蹲街弑〆低调 提交于 2020-01-13 06:50:47

问题


The FINAL TABLE clause is great for getting values back from DML in DB2, for example:

SELECT id
FROM FINAL TABLE
( 
  INSERT INTO mySchema.myTable (val)
  VALUES ('data')
)            

However, there doesn't seem to be a way to store the results of this query into another table, persisting the contents somewhere. For example, both of the following fail with the error "Data change table reference not allowed where specified." (I am running DB2 for i v7.1):

CREATE TABLE mySchema.otherTable AS (
SELECT id
FROM FINAL TABLE
( 
  INSERT INTO mySchema.myTable (val)
  VALUES ('data')
)
) WITH DATA      

After creating mySchema.otherTable in a separate CREATE TABLE statement, this also fails:

INSERT INTO mySchema.otherTable (ID)
SELECT id
FROM FINAL TABLE
( 
  INSERT INTO mySchema.myTable (val)
  VALUES ('data')
)

回答1:


Not sure if this works on i Series, but DB2 for LUW allows you to do this:

with i1 (id) as (
  SELECT id
  FROM FINAL TABLE
  ( 
    INSERT INTO mySchema.myTable (val)
    VALUES ('data')
  )
)
select * from new table (
  INSERT INTO mySchema.otherTable (ID) 
  select id from i1
)



回答2:


I tried to use the FINAL TABLE technique today on an IBM i at OS V7R1 and it wouldn't work as described on DB2 for LUW, when attempting to feed the identity column value to a second insert. I anticipate we'll get this ability eventually.

As an alternative, I was able to route the assigned identity column value to an SQL Global Variable using a SET command, and then use that Global Variable to assign the same identity column value to 2 subsequent inserts to 2 related association tables. For non-compiled SQL scripting, that is a good technique to use for a server side solution until we get the same ability as described on DB2 for LUW. A temp table would work as well.

create variable MY_SCHEMA.MY_TABLE_ID
;
set MY_SCHEMA.MY_TABLE_ID = 
    ( select ID 
      from final table ( insert into MY_SCHEMA.MY_TABLE values ('data') ) ) 
;
insert into MY_SCHEMA.MY_OTHER_TABLE ( ID, DATA ) 
values( MY_SCHEMA.MY_TABLE_ID, 'more data' )
;

From the V7R1 SQL Reference manual: Global variables have a session scope. This means that although they are available to all sessions that are active on the database, their value is private for each session.

For compiled SQL stored procedures, a variable with a SELECT INTO works fine too.



来源:https://stackoverflow.com/questions/25221966/db2-storing-results-from-final-table-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!