sql server - SQL : Retrieve inserted row IDs array / table -


i have following statement:

insert table1 (field1, field2) select f1, f2 table2 -- returns 20 rows 

after insert need know array/table of ids generated in table1.id int identity

thanx in advance.

use output clause (sql2005 , up):

declare @ids table(id int)  insert table1(field1, field2) output inserted.id @ids(id) select field1, field2 table2 

if want know rows table2 generated id in table1 (and field1 , field2 aren't enough identify that), you'll need use merge:

declare @ids table(table1id int, table2id int)  merge table1 t using table2 s on 1=0 when not matched     insert (field1, field2) values(s.field1, s.field2) output inserted.id, s.id @ids(table1id, table2id) 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -