数据库中已经有一个名为“ #TempTableName”的对象?

时间:2019-07-30 11:34:25

标签: sql sql-server stored-procedures

我有一个存储过程,我正在将最终记录移到IF ELSE语句中的临时表中

示例

IF(Condition)
BEGIN

     IF OBJECT_ID('tempdb..#Records') IS NOT NULL  DROP TABLE #Records

     SELECT *
     INTO #Records
     FROM TableName

     SELECT * FROM #Records
END
ELSE
    IF OBJECT_ID('tempdb..#Records') IS NOT NULL  DROP TABLE #Records

     SELECT *
     INTO #Records
     FROM TableName

     SELECT * FROM #Records
END

我的StoredProcedure与上述格式完全相同。它引发错误There is already an object named '#Records' in the database.

3 个答案:

答案 0 :(得分:0)

将if条件放在if块之外。...

  IF OBJECT_ID('tempdb..#Records') IS NOT NULL  DROP TABLE #Records


 IF(Condition)
BEGIN
     SELECT *
     INTO #Records
     FROM TableName
     SELECT * FROM #Records
END
ELSE
     SELECT *
     INTO #Records
     FROM TableName
     SELECT * FROM #Records
END

OR

只需将此temp表首先放入数据库中一次,然后创建存储过程

  drop table #records

执行此操作,然后创建您的存储过程。

答案 1 :(得分:0)

尝试一下对您有帮助

IF OBJECT_ID('tempdb..#Records') IS NOT NULL  DROP TABLE 
#Records

SELECT top 1 * INTO #Records FROM TableName where 1=0;

IF(1=1)
  BEGIN

   INSERT INTO #Records
   select * FROM TableName;

   SELECT * FROM #Records;
 END
ELSE
 BEGIN

   INSERT INTO #Records
   select * FROM TableName;

   SELECT * FROM #Records;
 END

答案 2 :(得分:0)

因为通过IF条件中已经存在的SQL对象编译SP时,同时在else中创建相同的表名。这样就行不通了。

我通常使用以下方式

SELECT top 0 *
         INTO #Records

    IF(Condition)
    BEGIN

    INSERT INTO #Records
         SELECT *
         FROM TableName

         SELECT * FROM #Records
    END
    ELSE
        INSERT INTO #Records
         SELECT *
         FROM TableName

         SELECT * FROM #Records
    END

DROP TABLE #Records

您只需执行 首先DROP TABLE #Records,然后尝试运行此SP