【问题标题】:Drop temp table within IF ELSE statement在 IF ELSE 语句中删除临时表
【发布时间】:2014-05-21 09:06:12
【问题描述】:

我在这里遇到了死锁,问题是我必须更改一个使用 3 个不同临时表的过程。让我们为对话起见将它们命名为#temptable1、#temptable2、#temptable3。 我不能在这里复制/粘贴整个过程,但总体思路是这样的,原始过程 (procedure1) 在过程的最开始创建#temptable1

create table #temptable1

然后使用 select/into 语句创建剩余的两个

select  T.Col
    ,   T.Col2
    ,   T.Col3
into   #temptable2
from   table1 T
where  T.BB>0

select  T.Col
    ,   T.Col2
    ,   T.Col3
into   #temptable3
from   table2 T
where  T.BB>0

drop table #temptable1
drop table #temptable2
drop table #temptable3

到目前为止,它工作正常,但我想做的是通过添加 if/else 语句来更改过程。因此看起来像这样,

declare @BBB nvarchar(32)

create table #temptable1


if @BBB='dd'

begin 

select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable2
    from   table1 T
    where  T.BB>0 and T.G='FDL'

    select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable3
    from   table2 T
    where  T.BB>0 and T.G='FDL'

    drop table #temptable1
    drop table #temptable2
    drop table #temptable3
end 

if @BBB='kk'

begin 

select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable2
    from   table1 T
    where  T.BB>0 and T.G='FD'

    select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable3
    from   table2 T
    where  T.BB>0 and T.G='FD'

    drop table #temptable1
    drop table #temptable2
    drop table #temptable3
end

else 

begin 

select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable2
    from   table1 T
    where  T.BB>0

    select  T.Col
        ,   T.Col2
        ,   T.Col3
    into   #temptable3
    from   table2 T
    where  T.BB>0

    drop table #temptable1
    drop table #temptable2
    drop table #temptable3
end

当我尝试创建新程序时,我收到此消息,

Msg 2714, Level 16, State 1, Procedure pPortfoliostest3, Line 412
There is already an object named '#temptable1' in the database.
Msg 2714, Level 16, State 1, Procedure pPortfoliostest3, Line 550
There is already an object named '#temptable2' in the database.
Msg 2714, Level 16, State 1, Procedure pPortfoliostest3, Line 711
There is already an object named '#temptable3' in the database.

这些行指示临时表在第二个 if 语句中的位置(如果 @BBB='kk')。 我尝试了不同的组合,但无济于事。有小费吗?感谢您的宝贵时间。

【问题讨论】:

  • 试着把那些drop table statements at the beginning of the code
  • 我会尽力让你知道
  • 不,不过还是谢谢

标签: sql-server tsql stored-procedures


【解决方案1】:

T-SQL 解析器非常原始。特别是,control 流不会影响对象名称何时进入范围并保持在范围内。

因此,您在 if 分支中使用的名称仍在范围内,并且在解析 else 分支时会导致冲突。

如果可能,将表定义移到存储过程的顶部,在任何控制流之前,并切换到INSERT ... SELECT ...而不是SELECT ... INTO ...;或者如果ifelse 分支之间的表定义不匹配,则需要为临时表使用不同的名称。


作为解析器原始程度的另一个示例,请考虑以下内容:

if 1=0
begin
    declare @a int
end
select @a

这会产生一个包含null 的结果集,而不是(如您所料)一个错误,指出未声明@a

【讨论】:

  • 非常感谢你的朋友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多