简体   繁体   中英

Insert into one table2 from table1 get the id and then insert into table3 SQL server

I came across a situation where

  1. I need to insert multiple rows of data from a table1 into table2
  2. With each row insert into table2, I need to get the scope ID and insert that with more data into table3

I have come up with something like below, but it appears it keeps inserting the same scope id over and over into table3.

insert into dbo.table2(name_client, phone_client)
SELECT name_client, phone_client
from dbo.table1 where name_client is not null

declare @clientID INT = SCOPE_IDENTITY()

insert into dbo.table3(......, client_id)
SELECT ......., @clientID from table1 --where some condition

You can use OUTPUT clause to get the inserted identity values to table variable. Use the table variable to insert into the third table.

Sample code is given below:

-- Declare table variable
DECLARE @tableName Table(ClientId INT,name_client VARCHAR(25), 
phone_client VARCHAR(25))

--Use OUTPUT clause to get results into table variable
insert into dbo.table2(name_client, phone_client)
OUTPUT inserted.ClientId, inserted.name_client, inserted.phone_client INTO @tableName
SELECT name_client, phone_client
from dbo.table1 where name_client is not null;

--Utilize the table variable to insert into third table
insert into dbo.table3(......, name_client, phone_client, client_id)
SELECT .......,name_client, phone_client, tv.clientID from @tableName tv 
--where some condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM