views:

1099

answers:

4

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.

Thanks in advance!

+1  A: 

Unfortunately I don’t think there is a way to get the GUID back.
Would need to do something like this:

Declare @id uniqueidentifier
Select @id = NewID()

INSERT into tablename (id, somename) VALUES (@id, 'somebody')

Select @id as myid
Iain Hoult
See my answer that uses OUTPUT.
Rob Garrison
+1  A: 

You are forced to use NewID(), there shouldn't be an issue with that, unless you also made your GUID the clustering key as well as the primary key, in which case I would skip the clustering key over to an identity field and leave the primary on a NC index.

Andrew
+1  A: 

you want to use NEWID()

    declare @id uniqueidentifier
    set @id  = NEWID()
    INSERT INTO [dbo].[tbl1]
           ([id])
     VALUES
           (@id)

    select @id

but clustered index problem are there in GUID . read this one tooNEWSEQUENTIALID() .These are my ideas ,think before use GUID as primary Key . :)

anishmarokey
+1 for NEWSEQUENTIALID
Christian Hayter
"The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type 'uniqueidentifier' in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression."
Scott Whitlock
+7  A: 

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

Rob Garrison
As anishmarokey mentions, you should be using NewSequentialID() to generate your GUIDs and not NewID().
Rob Garrison