I came across a situation where
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.