Safest way to get last record ID from a table

后端 未结 8 1162
遇见更好的自我
遇见更好的自我 2020-12-03 09:53

In SQL Server 2008 and higher what is the best/safest/most correct way

  1. to retrieve the ID (based on autoincrementing primary key) out of the database table?
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 10:42

    Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

    Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.

提交回复
热议问题