vrijdag 9 oktober 2009

Retrieving Newly Inserted ID of an Identity Column

I was busy reading up on articles and doing the daily questions on SQL Server Central when I was faced with a question on the OUTPUT clause.  As this was a clause that I was unaware of, I went online to research this clause. I discovered that among other things, this possibly is the most reliable method of retrieving the identity value of an identity column of a newly inserted record.

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:
  1. @@IDENTITY
  2. SCOPE_IDENTITY
  3. IDENT_CURRENT
All the above function will return the last identity value generated however the scope of each of the functions differs.

@@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.