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

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: