You can use @@IDENTITY
instead of SCOPE_IDENTITY()
to get the assigned identity value in the outer batch scope. The downside with that method is it returns the last assigned identity value on the connection, which can be different than desired if there are triggers on the table.
Alternatively, capture the SCOPE_IDENTITY()
value in the inner dynamic SQL scope and return as an output parameter:
DECLARE @ScopeIdentity numeric(38,0);
SELECT @InsertTSQL = 'INSERT INTO Test (col) Select col from Test2;SET @ScopeIdentity = SCOPE_IDENTITY();';
EXECUTE sp_executesql @InsertTSQL, N'@ScopeIdentity numeric(38,0) OUT', @ScopeIdentity = @ScopeIdentity OUT;
SELECT @ScopeIdentity AS ScopeIdentity;