--創建臨時表##ttb
create table ##ttb (p001 nvarchar(20),p002 nvarchar(40) ,p009 nvarchar(20) ,p013 datetime,p012 datetime  ,p014 int,p005 char(4),orderP5 int)
insert into  ##ttb
select pi001,pi002,pi009,pi013,pi012,PI014,p005='B',1 as orderP5 from dgmocpi where pi001 like '%B%'  and pi002 not like '%立式%' 
union all
select pi001,pi002,pi009,pi013,pi012,PI014,P005='B1',2 as orderP5 from dgmocpi where pi001 like '%B%'  and pi002 like '%立式%' 
union all
select pi001,pi002,pi009,pi013,pi012,PI014,P005='T',3 as orderP5 from dgmocpi where pi001 like '%T%'  and pi002 not like '%立式%' 
union all
select pi001,pi002,pi009,pi013,pi012,PI014,P005='T1',4 as orderP5 from dgmocpi where pi001 like '%T%'  and pi002 like '%立式%'  
union all
select pi001,pi002,pi009,pi013,pi012,PI014,P005='C',5 as orderP5 from dgmocpi where pi001 like '%C%'  and pi002 not like '%立式%'  
以上是創建臨時表并插入資料,我現在想將上面部分放入到下面語句中
exec( ' 
IF  EXISTS (SELECT 1 FROM  tempdb.DBO.sysobjects where name =''##ttb'')
begin
drop table ##ttb
end 
')請問該如何編寫?

解决方案 »

  1.   

    if object_id('tempdb..##ttb') is not null
    drop table  ##ttb 
      

  2.   

    exec('
    if object_id(''tempdb..##ttb'') is not null
    drop table  ##ttb '
    )
      

  3.   

    --try
    exec( ' 
    IF  EXISTS (SELECT 1 FROM  tempdb.DBO.sysobjects where name =''##ttb'') 
    begin 
    drop table ##ttb 
    end 
    else
    begin
      create table ##ttb (p001 nvarchar(20),p002 nvarchar(40) ,p009 nvarchar(20) ,p013 datetime,p012 datetime  ,p014 int,p005 char(4),orderP5 int) 
    insert into  ##ttb 
    select pi001,pi002,pi009,pi013,pi012,PI014,p005=''B'',1 as orderP5 from dgmocpi where pi001 like ''%B%''  and pi002 not like ''%立式%'' 
    union all 
    select pi001,pi002,pi009,pi013,pi012,PI014,P005=''B1'',2 as orderP5 from dgmocpi where pi001 like ''%B%''  and pi002 like ''%立式%'' 
    union all 
    select pi001,pi002,pi009,pi013,pi012,PI014,P005=''T'',3 as orderP5 from dgmocpi where pi001 like ''%T%''  and pi002 not like ''%立式%'' 
    union all 
    select pi001,pi002,pi009,pi013,pi012,PI014,P005=''T1'',4 as orderP5 from dgmocpi where pi001 like ''%T%''  and pi002 like ''%立式%''  
    union all 
    select pi001,pi002,pi009,pi013,pi012,PI014,P005=''C'',5 as orderP5 from dgmocpi where pi001 like ''%C%''  and pi002 not like ''%立式%''
    end
    ') 
      

  4.   


    我没看清楚,不好意思
    试试3楼mm的,顺便把这个mm拐回家