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?
You can get the GUID back by using OUTPUT. This works when you're inserting multiple records also.
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
Reference: Exploring SQL 2005’s OUTPUT Clause