Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Last active January 19, 2021 16:49
Show Gist options
  • Select an option

  • Save JerryNixon/c5cc66a2b06d4f45b30a6e04ce119984 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/c5cc66a2b06d4f45b30a6e04ce119984 to your computer and use it in GitHub Desktop.
Get the auto-generated key from a SQL insert operation
SET NOCOUNT ON
CREATE TABLE [Users]
(
[Id] INT PRIMARY KEY IDENTITY(1,1)
, [Name] VARCHAR(50) NOT NULL
)
GO
DECLARE @key int;
-- insert one (retrieve generated key)
-- warning: this only works in the most simple scenario
INSERT INTO [Users] ([Name])
VALUES ('Jerry');
SELECT @key = Id
FROM [Users]
WHERE [Name] = 'Jerry';
PRINT @key;
-- insert another (key is abiguous)
-- warning: this scenario illustrates an ambiguous race condition
INSERT INTO [Users] ([Name])
VALUES ('Jerry');
SELECT @key = Id
FROM [Users]
WHERE [Name] = 'Jerry';
PRINT @key;
-- insert another (output key with SCOPE_IDENTITY() - supports single record)
-- warning: SCOPE_IDENTITY() returns even if insert fails
INSERT INTO [Users] ([Name])
VALUES ('Jerry');
SELECT @key = Id
FROM [Users]
WHERE [Name] = 'Jerry';
PRINT SCOPE_IDENTITY();
-- insert another (output key with OUTPUT CLAUSE - supports multiple records)
-- note: this is the GOLDEN approach, works every single time
DECLARE @keys TABLE (Id int);
INSERT INTO [Users] ([Name])
OUTPUT inserted.Id INTO @keys
VALUES ('Jerry');
SELECT @key = Id FROM @keys;
PRINT @key;
GO
DROP TABLE [Users]
@JerryNixon

Copy link
Copy Markdown
Author

Output looks like this:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment