2014-03-07 177 views
-1

当我想最后得到插入ID为表我用这样的:获取列出所有最后插入的ID的一个表

insert into table1(col1,col2,col3) 
     values(val1,val2,val3) 

declare @last_id int = scope_identity() 

该得到的值现在我已经存储过程中插入多个项目:

insert into table1(col1,col2,col3) 
     select @val1,@val2,val3 from table2 where [email protected] //@value is a single value that is passed to procedure as argument 

现在我怎么能得到这些多行添加到table1的ID列表?

回答

2
declare @inserted table (Id int) 

insert into table1(col1,col2,col3) 
output inserted.Id into @inserted (Id) 
select @val1,@val2,val3 
from table2 
where [email protected] 

select * from @inserted 
1

SCOPE_IDENTITY()为您提供最后生成的标识列中的标识值。要获得所有新插入的值,您需要使用OUTPUT子句以及表变量。请参阅下文,您可以如何做到这一点

DECLARE @New_IDs TABLE(IDs INT) 


insert into table1(col1,col2,col3) 
OUTPUT inserted.Id_column INTO @New_IDs 
select @val1,@val2,val3 
from table2 
where [email protected] 

SELECT * FROM @New_IDs