SCOPE_IDENTITY() is Returning NULL instead of IDENTITY Value

libpekin 166 Reputation points
2024-12-23T20:23:37.25+00:00

Hello,

I'm using dynamic SQL to insert a default value into a table and want to return the SCOPE_IDENTITY() value for my surrogate key. However, SCOPE_IDENTITY() is returning NULL for some reason. Am I missing something?

Thanks for your assistance.

BEGIN
    DECLARE @SQL NVARCHAR(MAX),
            @SurrogateKey INT,
            @SchemaName VARCHAR(128) = 'dim',
            @TableName VARCHAR(128) = 'Sales',
            @NaturalKeyColumn VARCHAR(128) = 'SalesID',
            @NaturalKeyValue VARCHAR(40) = '100',
            @SurrogateKeyColumn VARCHAR(128) = 'SalesKey';

    SET @SQL = N'SELECT @SurrogateKey = ' + QUOTENAME(@SurrogateKeyColumn) + 
               ' FROM ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + 
               ' WHERE ' + QUOTENAME(@NaturalKeyColumn) + ' = @NaturalKeyValue';

    EXEC sp_executesql @SQL, N'@SurrogateKey INT OUTPUT, @NaturalKeyValue VARCHAR(40)', @SurrogateKey OUTPUT, @NaturalKeyValue;

    IF @SurrogateKey IS NULL
    BEGIN
        BEGIN TRANSACTION;

        SET @SQL = N'INSERT INTO ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + 
                   ' (' + QUOTENAME(@NaturalKeyColumn) + ', InferredFlag)
                    VALUES (@NaturalKeyValue, 1)';

        EXEC sp_executesql @SQL, N'@NaturalKeyValue VARCHAR(40)', @NaturalKeyValue;

        -- Check if the INSERT was successful
        IF @@ROWCOUNT > 0
        BEGIN
            SET @SQL = N'SELECT @SurrogateKey = SCOPE_IDENTITY()';

            EXEC sp_executesql @SQL, N'@SurrogateKey INT OUTPUT', @SurrogateKey OUTPUT;
        END

        COMMIT TRANSACTION;
    END

    SELECT @SurrogateKey;
END
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,290 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,675 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 118.9K Reputation points
    2024-12-23T21:37:22.2066667+00:00

    Try something like this:

    SET @SQL = N'INSERT INTO ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + 
                ' (' + QUOTENAME(@NaturalKeyColumn) + ', InferredFlag)
                VALUES (@NaturalKeyValue, 1) 
    			if @@rowcount > 0 select @SurrogateKey = scope_identity()'
    
    EXEC sp_executesql @SQL, N'@NaturalKeyValue VARCHAR(40), @SurrogateKey INT OUTPUT', @NaturalKeyValue, @SurrogateKey OUTPUT
    
    select @SurrogateKey
    

    The if probably can be omitted.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.