Safest way to get last record ID from a table

后端 未结 8 1116
遇见更好的自我
遇见更好的自我 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:33
    1.  SELECT MAX(Id) FROM Table
    
    0 讨论(0)
  • 2020-12-03 10:35

    And if you mean select the ID of the last record inserted, its

    SELECT @@IDENTITY FROM table
    
    0 讨论(0)
  • 2020-12-03 10:36

    SELECT LAST(row_name) FROM table_name

    0 讨论(0)
  • 2020-12-03 10:39

    You can try:

    SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)
    

    Where id is a primary key of the your_table

    0 讨论(0)
  • 2020-12-03 10:40

    One more way -

    select * from <table> where  id=(select max(id) from <table>)
    

    Also you can check on this link -

    http://msdn.microsoft.com/en-us/library/ms175098.aspx

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题