简体   繁体   English

从table1插入一个table2获取id然后插入table3 SQL服务器

[英]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我需要将 table1 中的多行数据插入 table2
  2. With each row insert into table2, I need to get the scope ID and insert that with more data into table3将每一行插入 table2,我需要获取 scope ID 并将更多数据插入 table3

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.

相关问题 sql server将数据从table1插入table2,其中table1 = table3数据 - sql server insert data from table1 to table2 where table1=table3 data 插入table1从table2,table3中选择,其中 - insert table1 select from table2,table3 where 从一个表1中选择多个值,在表2中查找并在表3中插入 - Select multiple values from one table1, find in table2 and insert in table3 PostgreSQL:将table1复制到table2和table3,但使用返回的table2值插入table3 - postgresql: copy table1 to table2 and table3, but use returned table2 values to insert into table3 SQL 获取 table1 的名称以及 table2 和 table3 的计数 - SQL get table1 names with a count of table2 and table3 从表2到表3的SQL INSERT SELECT - SQL INSERT SELECT from Table2 to Table3 根据 table3 中的条件从 table2 插入 table1 - Insert into table1 from table2 based on conditions from table3 遍历table1,从table2中提取信息并插入到Teradata中的table3中 - Loop through table1, extract information from table2 and insert into table3 in Teradata SQL - 如果表 1 中存在 id,则将记录插入表 2 - SQL - If id exists in table1, then insert record into table2 除了Table3中已经存在的条目之外,如何将Table1和Table2的交集插入到Table3中? - How can I insert into Table3 the intersection of Table1 and Table2, except the entries that already exist in Table3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM