In this post I’ll explain the 4 methods available to get the IDs of newly inserted rows when the table has an identity Id column.
This variable contains the last identity value generated by the current connection, is not limited to the scope of the code being executed. In case the current connection didn’t insert any row with an identity the property will have a NULL value.
This code will give you unexpected result if there is a trigger, running for inserts in TableA, that is inserting row in other tables with an identity. In this case the
@@IDENTITY variable will give you the ID inserted by the trigger, not the one inserted in the current scope.
This function will return the value of the last identity inserted in the current executing batch.
The following code
will return the last value inserted in TableA by our insert, even if other connections, or trigger fired by the current connection are inserting values with IDs.
This will be the best method to use in most of the cases.
This function returns the last identity value inserted in the specified table, regardless of the scope and connection.
This function is available in SQL Server 2005 and newer versions.
The output clause can be used to get IDs when inserting multiple rows.
This obviously will insert into
@NewIds the Ids generated by the current statement. Other connection or code executing in different scopes will not affect the result of the operation.
IDENT_CURRENT, also this function is available in SQL Server 2005 and newer versions.