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

3

6

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?

Vichy answered 6/9, 2012 at 13:21 Comment(0)
T
15

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
Tangent answered 6/9, 2012 at 13:27 Comment(0)
P
2

You can try this also.....

CREATE PROCEDURE [dbo].[SaveSingleColumnValueFromGrid]
(
    @TableName VARCHAR(200),
    @ColumnName VARCHAR (200),
    @CompareField VARCHAR(200),
    @CompareValue VARCHAR(200),
    @NewValue VARCHAR(200),
    @Result INT OUTPUT
)
AS
BEGIN
    DECLARE @SqlString NVARCHAR(2000),
            @id INTEGER = 0;


    IF @CompareValue = ''
        BEGIN

            SET @SqlString = 'INSERT INTO ' + @TableName + ' ( ' + @ColumnName +  ' )  VALUES ( ''' + @NewValue + ''' ) ; SELECT @id = SCOPE_IDENTITY()';
            EXECUTE sp_executesql @SqlString, N'@id INTEGER OUTPUT',  @id OUTPUT
        END
    ELSE
        BEGIN
            SET @SqlString = 'UPDATE ' + @TableName + ' SET ' + @ColumnName +  ' = ''' + @NewValue + '''  WHERE ' + @CompareField +  ' = ''' + @CompareValue + '''';
            EXECUTE sp_executesql @SqlString
            set @id = @@ROWCOUNT
        END


    SELECT @Result = @id
END
Pitch answered 15/9, 2014 at 16:31 Comment(0)
M
0

Yes it should be part of a dynamic sql that is what scope_identity() is for

Matti answered 6/9, 2012 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.