【问题标题】:T-SQL error object exists when separated in if/else blocks在 if/else 块中分隔时存在 T-SQL 错误对象
【发布时间】:2010-04-08 14:37:21
【问题描述】:

我收到错误消息:消息 2714,级别 16,状态 1,第 16 行 数据库中已经有一个名为“#mytemptable”的对象。

有很多方法可以解决它,但想知道为什么会发生这种情况。似乎 SQL Server 正在验证 if/else 语句的两个块?

declare @choice int
select @choice = 1

if @choice = 1
    begin
        select 'MyValue = 1' AS Pick into #my_temp_table
    end
else
    begin
        select 'MyValue <> 1' AS Pick into #my_temp_table
    end

select * from #my_temp_table

drop table #my_temp_table

如果表有不同的名称,它可以工作。或者,如果我创建临时表并使用 Insert Into... 也可以使用的语句。

【问题讨论】:

    标签: sql-server-2005 tsql


    【解决方案1】:

    请看这里:What is deferred name resolution and why do you need to care?

    基本上你需要先吃桌子

    所以发生的情况是,从 SQL Server 7 开始,对真实表启用了延迟名称解析,但对临时表没有启用。如果您将代码更改为使用真实表而不是临时表,则不会有任何问题

    这是另一种方式

     declare @choice int
        select @choice = 1
    
    declare @Value varchar(100)
     if @choice = 1
     select @Value = 'MyValue = 1'
     else
     select @Value = 'MyValue <> 1'
    
        select @Value AS Pick into #my_temp_table
        select * from #my_temp_table
    
        drop table #my_temp_table
    

    【讨论】:

      【解决方案2】:

      试试这个:

          declare @choice int
          select @choice = 1
      
      CREATE TABLE     #my_temp_table(
      Pick varchar(25)
      )
      
      
          if @choice = 1
              begin
                  INSERT INTO #my_temp_table 
                    select 'MyValue = 1'
              end
          else
              begin
                  INSERT INTO #my_temp_table 
                      select 'MyValue <> 1'
              end
      
          select * from #temptable
      
          drop table #temptable
      

      编辑对不起,我看到你试过这个,问题是为什么会发生这种情况。这是因为 SQL Server 在创建存储过程时会对其进行解析并检查命名冲突。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-13
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        • 2021-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多