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
?
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