Best way to get identity of inserted row?

后端 未结 14 2468
醉梦人生
醉梦人生 2020-11-21 07:06

What is the best way to get IDENTITY of inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY

14条回答
  •  梦谈多话
    2020-11-21 07:50

    Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL. This allows you create your own numeric sequence object in SQL Server and control how it increments.

    Here is an example:

    CREATE SEQUENCE CountBy1  
        START WITH 1  
        INCREMENT BY 1 ;  
    GO  
    

    Then in TSQL you would do the following to get the next sequence ID:

    SELECT NEXT VALUE FOR CountBy1 AS SequenceID
    GO
    

    Here are the links to CREATE SEQUENCE and NEXT VALUE FOR

提交回复
热议问题