Tag: if else

  • SQL Server: SELECT INTO inside both IF and ELSE blocks

    I ran across this problem earlier today, and thought I should address this here in case anyone is interested in my solution.

    When doing a SELECT INTO command against the same temp table in both IF and ELSE blocks, you will quickly learn that SQL Server complains that there “is already an object named ‘#temp’ in the database”. What one can do to avoid this problem is declare the temp table before the IF/ELSE block and insert into the table afterwards, but what if you want to use SELECT INTO instead?

    if @var = 1
    	select 'abc' into #temp;
    else
    	select 'def' into #temp;
    
    select * from #temp;
    

    (more…)