What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

后端 未结 7 1302
灰色年华
灰色年华 2020-11-22 06:49

I know Scope_Identity(), Identity(), @@Identity, and Ident_Current() all get the value of the identity column, but I woul

7条回答
  •  孤独总比滥情好
    2020-11-22 07:23

    Good question.

    • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

    • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

    • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

    • IDENTITY(): used when declaring a column in a table as an identity column.

    For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.

    To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

提交回复
热议问题