LanceZhang’s Blog

Dear friends, Welcome to my blog.

2 ways to retireve the uniqueidentification field after insert

Using uniqueidentifier field as primary key and set the default value as (newsequentialid()) or (newid()) is a good choose for some scenerio.

If you try to use SCOPE_IDENTITY() or @@IDENTITY to retireve the uniqueidentification ID after add new row, you will found that is not worked.

There are two solution to achieve the facing goal:

DECLARE @outputTable TABLE(ID uniqueidentifier)
INSERT INTO TABLE1(col1, col2)
OUTPUT INSERTED.ID INTO @outputTable
VALUES(‘value1’, ‘value2’)
SELECT ID FROM @outputTable

— mark your ID field as ROWGUID
INSERT INTO TABLE1(col1, col2)
VALUES(‘value1’, ‘value2’)
SELECT ROWGUIDCOL FROM TABLE1

April 1, 2011 Posted by | MSSQL | Leave a comment