create table #test (a int identity(1,1), b varchar(20), c varchar(20))
insert into #test (b,c) values (\'bvju\',\'hjab\')
insert into #test (b,c) values (\'bst\',\'
You can use the output clause. From the documentation (emphasis mine):
The OUTPUT clause returns information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements. The results can also be inserted into a table or table variable. Additionally, you can capture the results of an OUTPUT clause in a nested INSERT, UPDATE, DELETE, or MERGE statement, and insert those results into a target table or view.
like so:
create table #tempids (a int) -- a temp table for holding our identity values
insert into #test
(b,c)
output inserted.a into #tempids -- put the inserted identity value into #tempids
values
('bvju','hjab')
You then asked...
What if the insert is from a select instead?
It works the same way...
insert into #test
(b,c)
output inserted.a into #tempids -- put the inserted identity value into #tempids
select -- except you use a select here
Column1
,Column2
from SomeSource
It works the same way whether you insert from values, a derived table, an execute statement, a dml table source, or default values. If you insert 1000 records, you'll get 1000 ids in #tempids
.