Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

Can anyone tell me if there is an equivalent of SCOPE_IDENTITY() when using GUIDs as a primary key in SQL Server?

I don't want to create the GUID first and save as a variable as we're using sequential GUIDs as our primary keys.

Any idea on what the best way to retrieve the last inserted GUID primary key?

1 Answer

0 votes
by (40.7k points)

Below code will also work if you're inserting multiple records:

CREATE TABLE dbo.GuidPk (

    ColGuid uniqueidentifier NOT NULL DEFAULT NewSequentialID(),

    Col2    int              NOT NULL

)

GO

DECLARE @op TABLE (

    ColGuid uniqueidentifier

)

INSERT INTO dbo.GuidPk (

    Col2

)

OUTPUT inserted.ColGuid

INTO @op

VALUES (1)

SELECT * FROM @op

SELECT * FROM dbo.GuidPk

Note: You can get the GUID back by using OUTPUT. 

Refer to this link: Exploring SQL 2005’s OUTPUT Clause

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 8, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
asked Jul 30, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer

Browse Categories

...