簡體   English   中英

從table1插入一個table2獲取id然后插入table3 SQL服務器

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

我遇到了一種情況

  1. 我需要將 table1 中的多行數據插入 table2
  2. 將每一行插入 table2,我需要獲取 scope ID 並將更多數據插入 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

您可以使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM