簡體   English   中英

SQL:如何從一個表插入數據並輸出到臨時表,而第一個表具有額外的值

[英]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.IdUser.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM