Safest way to get last record ID from a table

后端 未结 8 1117
遇见更好的自我
遇见更好的自我 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:48
    SELECT IDENT_CURRENT('Table')
    

    You can use one of these examples:

    SELECT * FROM Table 
    WHERE ID = (
        SELECT IDENT_CURRENT('Table'))
    
    SELECT * FROM Table
    WHERE ID = (
        SELECT MAX(ID) FROM Table)
    
    SELECT TOP 1 * FROM Table
    ORDER BY ID DESC
    

    But the first one will be more efficient because no index scan is needed (if you have index on Id column).

    The second one solution is equivalent to the third (both of them need to scan table to get max id).

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

    I think this one will also work:

    SELECT * FROM ORDER BY id DESC LIMIT 0 , 1

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