Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 856
Jon Leach Avatar asked Sep 06 '12 13:09

Jon Leach


2 Answers

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
like image 160
AdaTheDev Avatar answered Oct 05 '22 09:10

AdaTheDev


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
like image 45
Rahul Garg Avatar answered Oct 05 '22 08:10

Rahul Garg