SCOPE_IDENTITY() for GUIDs? SCOPE_IDENTITY() for GUIDs? sql-server sql-server

SCOPE_IDENTITY() for GUIDs?


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)GODECLARE @op TABLE (    ColGuid uniqueidentifier)INSERT INTO dbo.GuidPk (    Col2)OUTPUT inserted.ColGuidINTO @opVALUES (1)SELECT * FROM @opSELECT * FROM dbo.GuidPk

Reference: Exploring SQL 2005’s OUTPUT Clause


There is no SCOPE_IDENTITY() equivalent when using GUIDs as primary keys, but you can use the OUTPUT clause to achieve a similar result. You don't need to use a table variable for output.

CREATE TABLE dbo.GuidTest (    GuidColumn uniqueidentifier NOT NULL DEFAULT NewSequentialID(),    IntColumn int NOT NULL)GOINSERT INTO GuidTest(IntColumn)OUTPUT inserted.GuidColumnVALUES(1)

The example above is useful if you want to read the value from a .Net client. To read the value from .Net you would just use the ExecuteScalar method.

...string sql = "INSERT INTO GuidTest(IntColumn) OUTPUT inserted.GuidColumn VALUES(1)";SqlCommand cmd = new SqlCommand(sql, conn);Guid guid = (Guid)cmd.ExecuteScalar();...


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 . :)