OUTPUT CLAUSE
Per BOL "Returns information from, or expressions based on, each row affected by an INSERT, UPDATE, or DELETE statement. These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements. Alternatively, results can be inserted into a table or table variable."
Example 1:
DECLARE @SomeTable TABLE ( id INT IDENTITY(1,1) , somevalue VARCHAR(50) )
INSERT INTO @SomeTable ( somevalue ) OUTPUT Inserted.ID VALUES ( 'some test value' )
Its as simple as that.
The identity values and other columns can also be "inserted" into a table variable ( very useful when not doing single inserts, but multiple inserts ) .
Example 2:
DECLARE @SomeTable TABLE ( id INT IDENTITY(1,1) , somevalue VARCHAR(50) )
-- Create a table variable to hold the output.
DECLARE @values TABLE ( id INT , somevalue VARCHAR(50) )
INSERT INTO @SomeTable ( somevalue )
OUTPUT Inserted.ID, Inserted.somevalue
INTO @values
VALUES ( 'some test value' )
SELECT * FROM @values
COMMON FUNCTIONS
To recap what the more commonly used functions for retrieving identity values are:
- @@IDENTITY
- SCOPE_IDENTITY
- IDENT_CURRENT
@@IDENTITY
Scope: any table in the current session across all scopes on the local server.
(This means that this function cannot be used on remote or linked servers )
SCOPE_IDENTITY
Scope: any table in the current session in the current scope
IDENT_CURRENT
Scope : specific table in any session and any scope.
I have always found the scope and session issues rather confusing. BOL has a very good example which clarifies this very well.