SQL:如何从一个 table 插入数据并输出到一个临时 table,其中包含第一个 table 的额外值

SQL: How do I insert data from one table and output to a temporary table with extra value from first table

我可以使用插入语句的OUTPUT关键字将新数据插入table并输出到临时table。

要插入另一个 table 的输入 table 有一个 Id 我需要传递给临时 table 但不是我要插入的 table进入。这个临时 table 稍后必须用于对另一个 table.

进行额外插入
INSERT INTO table1 (Name, Age)
OUTPUT inserted.Id, User.Id (??) INTO TemporaryTable
SELECT Name, Age FROM User

有办法吗?因为下一次插入需要新的table1.IdUser.Id,所以我可以迁移一些数据。

您是否在临时 table 的架构中包含了额外的列?

create table table1 
(
id int
,name varchar(50)
,age int
)

declare @TemporaryTable table -- or Create table #TemporaryTable
(                             
  id int,                     
  userid int -- defining the extra column                 
);                            

declare @extracolumn as int = 100; 
-- or declare @extracolumn as int = (select value from table where condition)
-- note that subqueries cannot be added directly in the output clause
-- so need to declare and set a variable that holds the value

insert into table1
output  inserted.id,@extracolumn into  @TemporaryTable -- or #TemporaryTable
values(1,'name',10)

select * from @TemporaryTable

输出为

id  userid
1   100

您可以使用 Variable 而不是使用 Temporary table,这样它就不会占用更多内存。

create table table1 
(
id int NOT NULL,
,name varchar(50)
,age int,
 PRIMARY KEY (id)
)

insert into table1 (name,age) values ('name', 10)                          

declare @extracolumn as int =  scope_identity() 
select @extracolumn 

在下一个插入操作中使用这个@extracolumn。