我想通过IF语句判断何时添加临时表
SQL语句如下
IF object_id('tempdb..#mytemp')  is NOT  null 
DROP TABLE #mytempif 1=1
select 1 AS 'A' into #mytemp 
else
select 2 AS 'B' into #mytemp但是执行缺报错
消息 2714,级别 16,状态 1,第 4 行
数据库中已存在名为 '#mytemp' 的对象。

解决方案 »

  1.   

    IF object_id('tempdb..#mytemp') is NOT null
    DROP TABLE #mytempif 1=1
    EXEC('select 1 AS ''A'' into #mytemp');
    else
    EXEC('select 2 AS ''B'' into #mytemp');
      

  2.   


    IF object_id('tempdb..#mytemp') is NOT null 
      DROP TABLE #mytempcreate table #mytemp (x int)if 1=1
    insert into #mytemp select 1 AS 'A' 
    else
    insert into #mytemp select 2 AS 'B'
      

  3.   

    在同一个批中,不能用if else 来分别引用同一个临时表.
      

  4.   

    IF object_id('tempdb..#mytemp') is NOT null
    DROP TABLE #mytemp
      

  5.   

    IF object_id('tempdb..#mytemp') is NOT null 
    DROP TABLE #mytempif 1=1
    select 1 AS 'A' into #mytemp 
    else
     insert into #mytemp select 2 AS 'B'