![](/img/trans.png)
[英]sql server insert data from table1 to table2 where table1=table3 data
[英]Insert into one table2 from table1 get the id and then insert into table3 SQL server
我遇到了一種情況
我想出了類似下面的東西,但它似乎一直在將相同的 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
您可以使用 OUTPUT 子句將插入的標識值獲取到表變量中。 使用 table 變量插入到第三個表中。
示例代碼如下:
-- 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.