DB2 storing results from final table clause

假装没事ソ 提交于 2019-12-04 20:24:17

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
)

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.

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