Retrieving id of inserted record: What to use @@IDENTITY or SCOPE_IDENTITY() or OUTPUT
This seems very basic information but need to know properly.
I need to find out or have the id of the records which I inserted in table.
ThisÂ requirement seems very simple but there could be various cases where you would not get the correct id just by using @@IDENTITY function.
Think of the case where you are inserting a record in table A and there is a trigger which fires as soon as there is a insert in table A which insert a record in table B. so in such case @@IDENTITY wont give you the correct id/pointer of inserted record.
So to deal with this issue you can use SCOPE_IDENTITY(). You will always get the last value you have inserted in table. However, it is noticed that sometimes in some scenarios SCOPE_IDENTITY() does not promise the correctness of results. May be due to parallelism or multiple inserts or bulk inserts in table(s). E.g. when you do … Insert Into Select <columns> from Table
Well, Microsoft recommends that “You do not use either of these functions in your queries when parallel plans are involved as they are not always reliable. Instead use the OUTPUT clause of INSERT statement to retrieve the identity value“.
I hope this will help you somewhere.
February 6, 2013
Â· Khilitchandra Prajapati Â· No Comments
Tags: Business Intelligence, General, IDENTITY, Interview Tips, OUTPUT, SCOPE_IDENTITY(), SQL Server Â· Posted in: Business Intelligence, Free, General, Interview QA, Quick Fix, Quick Tips, Script, SQL Server, SQL Server 2012, SQLServerPedia, T-SQL, Training, Tutorial