patternsqlModerate
Insert into select into multiple related tables using INSERT_IDENTITY
Viewed 0 times
tablesinsertintorelatedinsert_identityusingmultipleselect
Problem
Okay setting the scene. I have three tables, (
So for every row in
If I were to do this...
I'd get the
Is a
Table1, Table2 and DataTable) and I want to insert into Table1 and Table2 using DataTable as source.So for every row in
DataTable I want a row in Table1 and Table2, and Table2 needs to have the inserted id (PK) from Table1...If I were to do this...
INSERT INTO Table1 SELECT A, B, C FROM MyTable
INSERT INTO Table2 SELECT IDENTITY_INSERT(), D, E, F FROM MyTableI'd get the
ID of the last inserted record into Table1.Is a
CURSOR or WHILE loop the only ways to do this?Solution
A solution that might work for you is using the OUTPUT clause, which spits out all the inserted rows, so you can re-insert them into a different table. However, this puts limitations on foreign key constraints on Table2, if memory serves.
Anyway, the solution would look something like this:
MERGE, as opposed to the other DML statements, can reference other tables than just
More: http://sqlsunday.com/2013/08/04/cool-merge-features/
Anyway, the solution would look something like this:
MERGE INTO Table1 AS t1
USING MyTable ON 1=0 -- always generates "not matched by target"
WHEN NOT MATCHED BY TARGET THEN
-- INSERT into Table1:
INSERT (A, B, C) VALUES (t1.A, t1.B, t1.C)
--- .. and INSERT into Table2:
OUTPUT inserted.ID, MyTable.D, MyTable.E, MyTable.F
INTO Table2 (ID, D, E, F);MERGE, as opposed to the other DML statements, can reference other tables than just
inserted and deleted, which is useful for you here.More: http://sqlsunday.com/2013/08/04/cool-merge-features/
Code Snippets
MERGE INTO Table1 AS t1
USING MyTable ON 1=0 -- always generates "not matched by target"
WHEN NOT MATCHED BY TARGET THEN
-- INSERT into Table1:
INSERT (A, B, C) VALUES (t1.A, t1.B, t1.C)
--- .. and INSERT into Table2:
OUTPUT inserted.ID, MyTable.D, MyTable.E, MyTable.F
INTO Table2 (ID, D, E, F);Context
StackExchange Database Administrators Q#73635, answer score: 10
Revisions (0)
No revisions yet.