Recently, I was writing a stored procedure that, at one point, performs an insert into a table that has a GUID (uniqueidentifier) primary key. The default value for this column is set to NEWSEQUENTIALID().
Further along in the stored procedure, I needed the value of this newly-inserted GUID to use in another INSERT statement. Fortunately, T-SQL provides us with precisely what we need – the OUTPUT clause.
A quick demo:
The table DDL:
CREATE TABLE [dbo].[MyTable] ( [MyId] [uniqueidentifier] NOT NULL, [FirstName] [varchar](50) NULL, [LastName] [varchar](50) NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([MyId] ASC) ) GO ALTER TABLE [dbo].[MyTable] ADD CONSTRAINT [DF_MyTable_MyId] DEFAULT (newsequentialid()) FOR [MyId] GO
Example portion of sproc:
DECLARE @MyTempTable table (MyTempId uniqueidentifier);
INSERT INTO MyTable (
FirstName
, LastName
)
OUTPUT inserted.MyId INTO @MyTempTable
VALUES (
'Brian'
, 'Dobberteen'
);
DECLARE @NewlyInsertedId uniqueidentifier;
SELECT @NewlyInsertedId = MyTempId FROM @MyTempTable;
Thanks to the bit highlighted above on lines 7 and 15, we now have a reference to the newly inserted GUID and can use it as needed.
Additionally, the use of newsequentialid() here lessens the impact of using a GUID clustered index.
