views:

135

answers:

2

i have a procedure in which i am inserting record in employee table.nad getting empid by using @@identity ? when this procedure will be called by more than one user at same time,there can be possibility that it returns identity of some other employee inserted at same time.because there is no lock on identity by system?

--code --identity on for empid column
insert into employee (name) values ('sahil'); return @@identity

refer http://stackoverflow.com/questions/882460/sql-server-2005is-it-safe-to-use-identity for lock on identity issue

+7  A: 

You should be using SCOPE_IDENTITY() instead. However, @@IDENTITY refers to the current connection so other users won't affect you but there are other issues to consider.

More information here.

BobbyShaftoe
there is a know bug with scope_identity(), so watch out: http://blog.sqlauthority.com/2009/03/24/sql-server-2008-scope_identity-bug-with-multi-processor-parallel-plan-and-solution/
KM
+1  A: 

@@identity is not safe to use. If the table has a trigger with an insert to a differnt table with an identity that is the value that will be returned. Never use it to get the idnetity value you just inserted. You may think well I don't have a trigger now, but you never know when one might be added and you can go a long time before realizing that your data is hopelessly messed up.

HLGEM