Skip to content
Advertisement

CASE WHEN SQL Query executes condition in else even if first condition is true

I’m trying to check if data exists in a table. First I check whether the table exists then I use a SELECT statement to check whether the table is empty or not

I have this query which is not supposed to execute SELECT 1 FROM TableName if OBJECT_ID('TableName') returns NULL but this query goes on and executes

which of course throws an error

Invalid Object Name TableName

Advertisement

Answer

Try the following:

The error you are getting is a compilation error. Since it’s a single statement. SQL Server needs to build an execution plan, and can’t do this, if the table doesn’t exists.

By adding an IF the statement doesn’t need to be “compiled” if the condition is not met.

With dynamic SQL:

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