You don't need BEGIN TRAN
. Scope_Identity()
functions fine without it. Even if there are "simultaneous inserts". That is the whole point of the function--to return an answer for the current scope only.
Be aware that in less than SQL Server 2012, parallelism can break Scope_Identity()
, so you must use the query hint WITH (MAXDOP 1)
on your INSERT
statement if you want it to work properly 100% of the time. You can read about this problem on Microsoft Connect. (It is theoretically fixed in Cumulative Update package 5 for SQL Server 2008 R2 Service Pack 1, but some people seem to think that may not be 100% true).
There is also the OUTPUT
clause in SQL Server 2005 and up, which is another way to return data about your INSERT
, either by sending a rowset to the client or by outputting to a table. Be aware that receiving the rowset does not actually prove the INSERT
was properly committed... so you should probably use SET XACT_ABORT ON;
in your stored procedure. here's an example of OUTPUT
:
CREATE TABLE @AInsert(IDColumn);
INSERT dbo.TableA (OtherColumn) -- not the identity column
OUTPUT Inserted.IDColumn -- , Inserted.OtherColumn, Inserted.ColumnWithDefault
INTO @AInsert
SELECT 'abc';
-- Do something with @AInsert, which contains all the `IDColumn` values
-- that were inserted into the table. You can insert all columns, too,
-- as shown in the comments above