【问题标题】:Conditional statement with temp table creation error [duplicate]带有临时表创建错误的条件语句[重复]
【发布时间】:2015-07-29 19:13:23
【问题描述】:

我一直在绞尽脑汁,但看不出下面的查询有什么问题。
我创建了一个临时表,它可以保存两个值之一。
这个想法是,如果存储了1,它会执行下面代码的第一部分(This),如果是2,它会执行下面的代码(That)。
麻烦的是代码不会运行,因为它“似乎”认为代码的两个部分都将被执行......我认为。有什么想法吗?

create table #Globals(G1 smallint);
insert into #Globals values (1); 
--insert into #Globals values (2); 

if (select G1 from #Globals) = 1
  select 'This' as field1 into #x;
else if (select G1 from #Globals) = 2
  select 'That' as field1 into #x;

Msg 2714, Level 16, State 1, Line 8
There is already an object named '#x' in the database.

【问题讨论】:

  • 即使您尝试在第二次插入之前删除临时表,您也会得到相同的异常。请尝试改用我的建议。

标签: sql-server


【解决方案1】:

不用select into,只需在条件使用insert into之前创建#x

create table #x (field1 char(4));

if (select G1 from #Globals) = 1
    insert into #x(field1) values('This');
else if (select G1 from #Globals) = 2
    insert into #x(field1) values('That');

另一种选择是使用CASE

create table #x (field1 varchar(7));
declare @g1 int
select @g1 = g1 from #globals

insert into #x(field1) values(
    case when @g1 = 1 then 'this'
         when @g1 = 2 then 'that'
    else
         'default'
    end
);

case 选项将允许您使用多个不同的选项(您可以根据需要指定多少个 when 子句),而且我还演示了一种仅查询临时表一次而不是每个 if.. .else if... else if... 分支。 (当然,你可以用 if...else 做同样的事情)

【讨论】:

    【解决方案2】:

    你应该使用EXISTS作为代码的逻辑流程:

    if exists (select G1 from #Globals where G1 = 1)
      begin
        select 'This' as field1 into #x;
      end
    else if exists (select G1 from #Globals where G1 = 2)
      begin
        select 'That' as field1 into #x;
      end
    

    【讨论】:

    • 这并不能解决 OP 的问题
    • 然后我会假设临时表已经在该会话中创建。我始终确保临时表的删除表是我的代码的最后一行,以确保在测试/运行临时操作时,我不会收到此错误。除非两个条件都为真,否则无法创建两次临时表,在这种情况下,问题在于您的逻辑,而不是流程。
    • 我在新会话中使用不同的临时表名称 (#x987) 运行了上述代码,但仍然收到错误消息 (Msg 2714, Level 16, State 1, Line 11 There is already a object在数据库中命名为“#x987”。)
    猜你喜欢
    • 2023-02-03
    • 2019-05-27
    • 2020-06-08
    • 1970-01-01
    • 2012-03-28
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多