Lets say I have two tables
tblA (
tableAID INT IDENTITY(1,1),
foo VARCHAR(100))
tblB (
tableBID INTIDENTITY(1,1),
tableAID INT,
bar varchar(100))
tblB.tableAID is a FK to tblA.
I want to insert a bunch of records (pulled from some other table in the system) into this pair of tables. I need to know what the ID from inserting into tblA is before I can insert into tblB.
Is there any way to do this without processing it row-by-row?
In SQL Server 2005 and later, you can use the OUTPUT clause to pass the new key values into a second table:
Other possibilies exist in SQL Server 2008 with “composable DML” and the MERGE statement.
Added in response to comment: