[英]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. 我创建了一个存储过程,该存储过程根据一个条件返回表的最后插入行的ID。
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 消息2714,级别16,状态6,过程Test_Procedure,第15行
There is already an object named 'tempId' in the database. 数据库中已经有一个名为“ tempId”的对象。
The bit I'm not understanding is tempId
is used as a variable not as a table. 我不明白的一点是tempId
用作变量而不是表。 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. 当前,您的“选择进入”正在数据库上创建表“ tempId”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.