[英]Insert into one table2 from table1 get the id and then insert into table3 SQL server
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.我想出了类似下面的东西,但它似乎一直在将相同的 scope id 一遍又一遍地插入到 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.您可以使用 OUTPUT 子句将插入的标识值获取到表变量中。 Use the table variable to insert into the third table.
使用 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.