How to obtain SCOPE_IDENTITY() from INSERT run in EXEC() statement

Jon Leach picture Jon Leach · Sep 6, 2012 · Viewed 23.5k times · Source

I am building a dynamic insert statement within a stored procedure.

I build up the sql syntax in a variable and then execute it with EXEC(@VarcharVariable).

The SQL insert works fine but when I execute SET @Record_ID = Scope_Identity() afterwards, I don't get a value.

How can I capture this? Do I need to wrap it into the EXEC?

Answer

AdaTheDev picture AdaTheDev · Sep 6, 2012

Basic example, using sp_executesql

DECLARE @sql NVARCHAR(MAX)
DECLARE @Id INTEGER

SET @sql = 'INSERT MyTable (Field1) VALUES (123); SELECT @Id = SCOPE_IDENTITY()'
EXECUTE sp_executesql @sql, N'@Id INTEGER OUTPUT', @Id OUTPUT

-- @Id now has the ID in