简体   繁体   中英

There already exists an object in the database SQL Server

I have created a stored procedure that returns the id of last inserted row of a table based on one condition.

Condition is such that if the row being inserted already exists then it takes identity column of the row otherwise it inserts a new row into the table.

To do this, I have written the following code in a stored procedure

ALTER PROCEDURE [dbo].[Test_Procedure] 
    @description nvarchar(max) 
AS
BEGIN
    DECLARE @tempId int;

    SELECT CommentId 
    INTO tempId 
    FROM TestTable 
    WHERE description = @description;

    IF @tempId IS NULL
    BEGIN
        INSERT INTO TestTable 
        VALUES (@description);

        SELECT scope_identity();
    END
    ELSE 
    BEGIN
        SELECT @tempId FROM dual;
    END

    DROP TABLE tempId;
END

When I run the above stored procedure, first time it ran successfully and then on wards it started throwing the following error message

Msg 2714, Level 16, State 6, Procedure Test_Procedure, Line 15
There is already an object named 'tempId' in the database.

The bit I'm not understanding is tempId is used as a variable not as a table. I have seen people with the similar problem but in their case they used temporary tables

I really appreciate your help in resolving the above issue.

Try this syntax for setting your variable.

SELECT @tempId  = CommentId from TestTable where description = @description;

Currently your 'select into' is creating a table 'tempId' on the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM