SQL Insert Into Temp Table in both If and Else Blocks

后端 未结 8 1931
自闭症患者
自闭症患者 2020-12-10 12:52

I\'m trying to populate a temp table based on the result of a condition in SQL 2005. The temp table will have the same structure either way, but will be populated using a d

相关标签:
8条回答
  • 2020-12-10 13:41

    Answering 8 years late, but I'm surprised nobody thought of:

    select * into #MyTempTable from...
    where 1=2
    
    IF -- CONDITION HERE
    insert into #MyTempTable select...
    ELSE
    insert into #MyTempTable select...
    

    Simple, quick, and it works. No dynamic sql needed

    0 讨论(0)
  • 2020-12-10 13:43

    this code may help you

    --creating temptable using columns of two existing tables
    --you can create your temp table Using other methods
    
    select top 0 VI.*,VU.FullName
    into #mytemptable
    from dbo.Items VI inner join
         dbo.Users as VU 
         on VU.Id=VI.Id
    
    --insert your data base on your condition
    if(i<2) --First Condition
    begin
    INSERT INTO #mytemptable
    SELECT VI.*,VU.FullName 
    from dbo.Items VI inner join
         dbo.Users as VU 
         on VU.Id=VI.Id
    end
    Else if(2<i) --Second Condition
    begin
    INSERT INTO #mytemptable
    SELECT VI.*,VU.FullName 
    from dbo.Items VI inner join
         dbo.Users as VU 
         on VU.Id=VI.Id
    end
    
    select * from #mytemptable --show result
    
    drop table #mytemptable --drop table if its needed
    

    this code works in sql server 2014 i don't know if it works in sql 2005 or not

    0 讨论(0)
提交回复
热议问题