Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temp table already exists

Tags:

sql

sql-server

Hi I have a temporary table in which I am trying to insert records based on a where condition but it throws an error that it already exists. I have tried to change the names but that is not the issue as the temporary tables are delete when the session ends.

I think I am writing the query right.

   SELECT [Name]
        INTO #TEMP_REJECT
        FROM #TEMP_VALIDATION
        WHERE Name = @Name

I am trying to insert #TEMP_REJECT FROM #TEMP_VALIDATION

Error message

"There is already an object named '#TEMP_REJECT' in the database."

Please suggest.

Thank you for your help. R

like image 645
BRDroid Avatar asked Oct 17 '25 14:10

BRDroid


1 Answers

SQL Server won't tell you that a table doesn't exist if it doesn't.

I suggest that you add

IF OBJECT_ID('tempdb..#TEMP_REJECT') IS NOT NULL
    DROP TABLE #TEMP_REJECT

in front of your select statement. This guarantees that the temp table won't exist when the select is executed.

So your statement becomes

 IF OBJECT_ID('tempdb..#TEMP_REJECT') IS NOT NULL
      DROP TABLE #TEMP_REJECT

 SELECT [Name]
            INTO #TEMP_REJECT
            FROM #TEMP_VALIDATION
            WHERE Name = @Name
like image 108
DeanOC Avatar answered Oct 20 '25 02:10

DeanOC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!