Best way to get identity of inserted row?

后端 未结 14 2448
醉梦人生
醉梦人生 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: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)
    

提交回复
热议问题