Link to home
Start Free TrialLog in
Avatar of brettr
brettr

asked on

Inserting into one table and using IDENTITY of another

I'm looping through one table and inserting into another.  The IDENTITY value for the target table is coming from a 3rd table.  The code below is wrong but expresses what I'm trying to do.  I need to insert into table1 first and use its IDENTITY value for col1 in table2.  So, the table1 insert needs to move into the looping through table3.  How can this be done?
insert into table1 (col1, col2, col3)
values(1, 2, 1)

insert into table2 (col1, col2, col3)
select SCOPE_IDENTITY(), 1, 1)
from table3

Open in new window

Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Do you mean like this:

INSERT INTO table1(col1, col2, col3)
VALUES(1, 2, 1);

DECLARE @ID BIGINT;
SELECT @ID = SCOPE_IDENTITY();

INSERT INTO table2(col1, col2, col3)
SELECT @ID, 1, 1
FROM table3;

Now, to be clear, you are not selecting any values at all from table 3. You appear to be using it for its number of rows? Is that what you mean to do?
Avatar of brettr
brettr

ASKER

My example was simple.  I am selecting some values from table3 but some are hard coded.  I should have shown that better.

Your example does basically the same as mine, which won't work because it will continue inserting the same ID into table2.  That column is a PK.  

table1 should insert just before each insert into table2.  This way, table2 gets a new ID for its PK.
Use the OUTPUT clause:

INSERT INTO TestA (TestA.Val1, TestA.Val2)
OUTPUT Inserted.* INTO TestB
VALUES (2,4)

SELECT * FROM TestA
SELECT * FROM TestB
SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of brettr

ASKER

@mwvisa1

Pretty close.  table1 and table2 match against empid.  Doesn't matter which ident goes into table2.  Just that the ident being inserted needs to match against the correct emptid.

I'm trying the OUTPUtT technique mentioned.  Thanks.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial