Best way to get identity of inserted row?

后端 未结 14 2414
醉梦人生
醉梦人生 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 08:01

    @@IDENTITY is the last identity inserted using the current SQL Connection. This is a good value to return from an insert stored procedure, where you just need the identity inserted for your new record, and don't care if more rows were added afterward.

    SCOPE_IDENTITY is the last identity inserted using the current SQL Connection, and in the current scope -- that is, if there was a second IDENTITY inserted based on a trigger after your insert, it would not be reflected in SCOPE_IDENTITY, only the insert you performed. Frankly, I have never had a reason to use this.

    IDENT_CURRENT(tablename) is the last identity inserted regardless of connection or scope. You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.

    0 讨论(0)
  • 2020-11-21 08:03

    The best (read: safest) way to get the identity of a newly-inserted row is by using the output clause:

    create table TableWithIdentity
               ( IdentityColumnName int identity(1, 1) not null primary key,
                 ... )
    
    -- type of this table's column must match the type of the
    -- identity column of the table you'll be inserting into
    declare @IdentityOutput table ( ID int )
    
    insert TableWithIdentity
         ( ... )
    output inserted.IdentityColumnName into @IdentityOutput
    values
         ( ... )
    
    select @IdentityValue = (select ID from @IdentityOutput)
    
    0 讨论(0)
提交回复
热议问题