【问题标题】:Insert into one table2 from table1 get the id and then insert into table3 SQL server从table1插入一个table2获取id然后插入表SQL server
【发布时间】:2020-04-08 00:09:36
【问题描述】:

我遇到了一种情况

  1. 我需要将table1中的多行数据插入table2中
  2. 将每一行插入 table2,我需要获取范围 ID 并将更多数据插入 table3

我想出了类似下面的东西,但它似乎不断将相同的范围 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

【问题讨论】:

  • @clientID 只能保存一个值,它不能保存一个列表。而SCOPE_IDENTITY() 只能获取单个值。我想你想要OUTPUT CLAUSE
  • 我没有从 table1 到 table3 的连接怎么可能? @DaleK

标签: sql sql-server


【解决方案1】:

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

【讨论】:

  • 这行不通,因为我没有从第一个表到第三个表的内部联接。您的表变量声明也缺少表类型。 .@Venkataraman。
  • 对不起。我已经纠正了。我提供了示例方法。由于您没有提供任何示例数据以及您想要实现的目标,这只是一种解决问题的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多