Skip to content
Advertisement

Table “already exists” after dropping with if exists

I got a pretty complex SQL that finally forced me to use a temp table to work around.

Essentially it looks like this:

However, I get an error message saying an object with the name #MYTEMPTABLE already exists in the database after a call with an error (which is rather likely if the customer/tester screws up some data).

Advertisement

Answer

It might DROP TABLE fail on your check condition, it might check from TempDB.INFORMATION_SCHEMA.COLUMNS table instead of sys.tables table

sqlfiddle

If your SQL server version was higher than 2016, you can try to use DROP TABLE IF EXISTS

if your SQL server version didn’t support that, you can check OBJECT_ID IS NOT NULL which represnt temp table exists in your system

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement