How can I retrieve the identities of rows that were inserted through insert…select?

后端 未结 4 1522
悲哀的现实
悲哀的现实 2020-12-29 16:42

I am inserting records through a query similar to this one:

insert into tbl_xyz select field1 from tbl_abc

Now I would like to retreive th

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 17:20

    @@IDENTITY will return you the last inserted IDENTITY value, so you have two possible problems

    1. Beware of triggers executed when inserting into table_xyz as this may change the value of @@IDENTITY.

    2. Does tbl_abc have more than one row. If so then @@IDENTITY will only return the identity value of the last row

    Issue 1 can be resolved by using SCOPE__IDENTITY() instead of @@IDENTITY Issue 2 is harder to resolve. Does field1 in tbl_abc define a unique record within tbl_xyz, if so you could reselect the data from table_xyz with the identity column. There are other solutions using CURSORS but these will be slow.

提交回复
热议问题