sql-server – 在IF ELSE语句中删除临时表

前端之家收集整理的这篇文章主要介绍了sql-server – 在IF ELSE语句中删除临时表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在这里遇到了僵局,问题是我必须改变一个使用3个不同临时表的过程.让我们为了对话,将它们命名为#temptable1,#temptable2,#temptable3.
我不能在这里复制/粘贴整个过程,但总体思路是这样的,原始过程(procedure1)在过程的最开始创建#temptable1
  1. create table #temptable1

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

  1. select T.Col,T.Col2,T.Col3
  2. into #temptable2
  3. from table1 T
  4. where T.BB>0
  5.  
  6. select T.Col,T.Col3
  7. into #temptable3
  8. from table2 T
  9. where T.BB>0
  10.  
  11. drop table #temptable1
  12. drop table #temptable2
  13. drop table #temptable3

在此之前它工作正常,但我想要做的是通过添加if / else语句来改变过程.因此,看起来像那样,

  1. declare @BBB nvarchar(32)
  2.  
  3. create table #temptable1
  4.  
  5.  
  6. if @BBB='dd'
  7.  
  8. begin
  9.  
  10. select T.Col,T.Col3
  11. into #temptable2
  12. from table1 T
  13. where T.BB>0 and T.G='FDL'
  14.  
  15. select T.Col,T.Col3
  16. into #temptable3
  17. from table2 T
  18. where T.BB>0 and T.G='FDL'
  19.  
  20. drop table #temptable1
  21. drop table #temptable2
  22. drop table #temptable3
  23. end
  24.  
  25. if @BBB='kk'
  26.  
  27. begin
  28.  
  29. select T.Col,T.Col3
  30. into #temptable2
  31. from table1 T
  32. where T.BB>0 and T.G='FD'
  33.  
  34. select T.Col,T.Col3
  35. into #temptable3
  36. from table2 T
  37. where T.BB>0 and T.G='FD'
  38.  
  39. drop table #temptable1
  40. drop table #temptable2
  41. drop table #temptable3
  42. end
  43.  
  44. else
  45.  
  46. begin
  47.  
  48. select T.Col,T.Col3
  49. into #temptable2
  50. from table1 T
  51. where T.BB>0
  52.  
  53. select T.Col,T.Col3
  54. into #temptable3
  55. from table2 T
  56. where T.BB>0
  57.  
  58. drop table #temptable1
  59. drop table #temptable2
  60. drop table #temptable3
  61. end

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

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

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

解决方法

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

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

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

作为解析器原始性的另一个示例,请考虑以下事项:

  1. if 1=0
  2. begin
  3. declare @a int
  4. end
  5. select @a

这会生成一个包含null的结果集,而不是(正如您可能预期的那样)一个错误,表示未声明@a.

猜你在找的MsSQL相关文章