SQL - create temp table in if else condition but error with aleady object

WONG Tony 161 Reputation points
2023-08-16T04:09:38.35+00:00

i wish to insert different sql result into SAME tempTable but error with already TempTable object

if @abc = 1

select * into #TmpTable from TestTable where...

else if @abc = 2

select * into #TmpTable from TestTable where...

But there is already an object named...

SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-08-16T06:04:37+00:00

    Hi @WONG Tony

    select * into #TmpTable from TestTable where...

    SELECT INTO statement is one of the easy ways to create a new table and then copy the source table data into this newly created table.

    The insertion statements for two different conditions in your If statement use the SELECT INTO statement. I am not sure if this is the source of the problem. (There is not enough data to test).

    My idea is to create #TmpTable before if condition and use this insertion statement in the if condition.

    insert into #TmpTable select * from TestTable where ...
    

    Best regards,

    Percy Tang

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Ronen Ariely 15,206 Reputation points
    2023-08-16T04:18:38.2366667+00:00

    But there is already an object named...

    You can drop the table if it exists before you start by using

    DROP TABLE IF EXISTS TmpTable;
    -- now start the if...
    
    

    You can also use a block of code in the if and excite DROP TABLE separately in each if condition


  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-08-16T21:34:03.97+00:00

    Yes, this is correct. In the same batch or stored procedure, you cannot have two statements to create the same temp table, no matter you do it with CREATE TABLE or SELECT INTO. And it does not matter if the resulting schema is the same or not. It is entirely outlawed. And this is a compile-time error, not a run-time error.

    The remedy is as Percy suggests, create the table explicitly with CREATE TABLE once.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.