当我想将最后一个插入的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 value=@value //@value is a single value that is passed to procedure as argument
现在如何获取添加到table1的这些多行的ID列表?
答案 0 :(得分: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 value=@value
select * from @inserted
答案 1 :(得分: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 value=@value
SELECT * FROM @New_IDs