Connecting Tech Pros Worldwide Forums | Help | Site Map

2 linked inserts in one statement

Newbie
 
Join Date: Apr 2009
Posts: 1
#1: Apr 23 '09
I'd like to insert record into GROUP table, get autogenerated value group_id and then insert record into another table, USER, with this group_id as a foreign key.
Code below works perfect, but since this possibility is not documented, I'm slightly aware. Would you recommend this way or do you know a better way?
DB2 v8.1. If you are going to test this query in Control Center be aware that you need to run commit after this.
I've put DDL below. Thanks a lot !



Expand|Select|Wrap|Line Numbers
  1. with tmp1 as 
  2. (select group_id
  3. from FINAL TABLE (INSERT INTO GROUP (group_name)
  4.      VALUES ('test'))),
  5. tmp2 as 
  6. (select count(*) as num
  7. from FINAL TABLE (INSERT INTO USER (group_id, user_id)
  8.      select group_id, 'test_user' from tmp1)
  9. )
  10. select num from tmp2;

DDL:
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE "GROUP" (
  2.   "GROUP_ID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (  
  3.             START WITH +1  
  4.             INCREMENT BY +1  
  5.             MINVALUE +1  
  6.             MAXVALUE +2147483647  
  7.             NO CYCLE  
  8.             NO CACHE  
  9.             NO ORDER ) , 
  10.    "GROUP_NAME" VARCHAR(30) NOT NULL);
  11.  
  12. ALTER TABLE "GROUP" 
  13.     ADD PRIMARY KEY
  14.         ("GROUP_ID");
  15.  
  16.  
  17. CREATE TABLE "USER" (
  18.   "GROUP_ID" INTEGER NOT NULL , 
  19.   "USER_ID" VARCHAR(64) NOT NULL); 
  20.  
  21.  
  22. ALTER TABLE "USER" 
  23.   ADD CONSTRAINT "GROUP_ID_FK" FOREIGN KEY
  24.         ("GROUP_ID")
  25.     REFERENCES "GROUP"
  26.         ("GROUP_ID")
  27.     ON DELETE CASCADE
  28.     ON UPDATE RESTRICT
  29.     ENFORCED
  30.     ENABLE QUERY OPTIMIZATION;
  31.  

Reply