[英]SQL: How do I insert data from one table and output to a temporary table with extra value from first table
我可以使用insert語句的OUTPUT
關鍵字將新數據插入表並輸出到臨時表。
要插入到另一個表中的輸入表具有一個ID,我需要將該ID傳遞給臨時表,而不是我要插入的表。 此臨時表以后將不得不用於對另一個表進行額外的插入。
INSERT INTO table1 (Name, Age)
OUTPUT inserted.Id, User.Id (??) INTO TemporaryTable
SELECT Name, Age FROM User
有辦法嗎? 因為下插入所需的新table1.Id
與User.Id
,這樣我就可以遷移一些數據。
除了使用臨時表,還可以使用變量,以便它不會占用更多內存。
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。
您是否在臨時表的架構中包括了額外的列?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.