SQL:如何从一个表插入数据并输出到临时表,而第一个表具有额外的值

时间:2018-07-03 05:41:11

标签: sql-server tsql migration temp-tables insertion

我可以使用insert语句的export R_LIBS_USER=~/my/custom/folder/lib R 关键字将新数据插入表中并输出到临时表中。

要插入到另一个表中的输入表具有一个ID,我需要将该ID传递给临时表,而不是我要插入的表。此临时表以后将不得不用于对另一个表进行额外的插入。

OUTPUT

有办法吗?因为下一次插入将需要带有INSERT INTO table1 (Name, Age) OUTPUT inserted.Id, User.Id (??) INTO TemporaryTable SELECT Name, Age FROM User 的新table1.Id,所以我可以迁移一些数据。

2 个答案:

答案 0 :(得分:2)

代替使用临时表,可以使用Variable,以便它不会占用更多内存。

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。

答案 1 :(得分:1)

您是否已在临时表的架构中包括了额外的列?

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
相关问题