Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I know Scope_Identity(), Identity(), @@Identity, and Ident_Current() all get the value of the identity column, but I would love to know the difference.

Part of the controversy I'm having is what do they mean by scope as applied to these functions above?

I would also love a simple example of different scenarios of using them?

1 Answer

0 votes
by (40.7k points)

@@IDENTITY: This returns the last identity value which is generated on your SQL connection (SPID). But, 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(): This returns the last identity value which is generated in the current scope (i.e. stored procedure, trigger, function, and so on).

IDENT_CURRENT(): This returns the last identity value for a specific table. Never use this to get the identity value from an INSERT, as it's the matter of race conditions (i.e. multiple connections inserting rows on the same table).

IDENTITY(): This is used when you are declaring a column in a table as an identity column.

Conclusion: If you are inserting rows, and want to know the value of the identity column for the row that you just inserted, then always use SCOPE_IDENTITY().

For more information, you can refer to http://msdn.microsoft.com/en-us/library/ms187342.aspx.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 25, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...