ERROR: There is already an object named '#temp' in the database

ERROR: There is already an object named '#temp' in the database

我想在存储过程中包含与以下代码类似的代码。但是当我执行它时,我得到这个错误:

There is already an object named '#temptable' in the database.

代码:

IF 1=1
    SELECT
        [col1] = 'inside IF 1',
        [col2] = 'inside IF 2'
    INTO
        #temptable
ELSE
    SELECT
        [col1] = 'inside Else 1',
        [col2] = 'inside Else 2',
        [col3] = 'inside Else 3'
    INTO
        #temptable

有办法解决吗?请注意 ELSE 块有 3 列,而 IF 块有 2 列进入 #temptable

这是一个解析错误。您正试图在同一批次中两次创建相同的对象。后者永远不会是 运行 没关系,语句将失败,因为解析器看到您尝试创建 #temptable 两次。

就像 Larnu 已经说过的,这是一个解析错误。它看到您试图多次创建相同的 table,但不知道只能访问其中一个。

根据此临时 table 的使用方式,可能有更好的方法来重构代码,但根据提供的内容进行工作,您有几个选择:

  1. 使用动态查询对解析器隐藏 SQL。动态查询通常不受欢迎,应尽可能避免使用。 (这已更新为使用全局温度 table 来解决范围问题)
IF 1=1
  EXEC('SELECT
    [col1] = ''inside IF 1'',
    [col2] = ''inside IF 2''
  INTO
    ##temptable')
ELSE
  EXEC('SELECT
    [col1] = ''inside Else 1'',
    [col2] = ''inside Else 2'',
    [col3] = ''inside Else 3''
  INTO
    ##temptable')
  1. 如果您提前知道所有列名,那么您可以 CREATE 包含所有可能列的 #temptable,并且在您的条件逻辑中,您可以使用 ALTER TABLE 来删除未使用的列。
CREATE TABLE #temptable (
    col1    varchar(10),
    col2    varchar(10),
    col3    varchar(10)
)

IF  1 = 1
BEGIN
    INSERT  INTO #temptable (col1, col2)
    SELECT
        col1 = 'inside IF 1',
        col2 = 'inside IF 2'

    ALTER TABLE #temptable DROP COLUMN col3
END
ELSE
BEGIN
    INSERT  INTO #temptable (col1, col2, col3)
    SELECT
        col1    = 'inside Else 1',
        col2    = 'inside Else 2',
        col3    = 'inside Else 3'
END