Skip to content
Advertisement

SQL: IF OBJECT_ID() and IF EXISTS don’t work in conjunction with UPDATE statement

I am using SQL Server 2017, I have a View called Foo, what I’m trying to do is to check if Foo is a user-defined table, if Yes, do an UPDATE, else do not do anything.

Here I check if the Foo exist and if it is a user-defined table (xtype='U'). Since Foo is a View, so xtype='U' should be false and the UPDATE should not execute, but the problem is that the UPDATE still execute, and error occurred.

When I execute the sql query below, indeed there is no record is returned, so the EXISTS should return false.

I’ve also tried this, but same problem, UPDATE still execute.

But, if I change the UPDATE statement into say a PRINT statement, then it works fine.

In this case, A is not printed, and the command executed successfully.

So, my question is why the IF EXISTS or IF OBJECT_ID I used above don’t work with UPDATE? Am I missing something or I am doing it wrong?

Thanks.

Advertisement

Answer

You can’t put the update directly behind the IF OBJECT_ID… however, you can execute the SQL this way:

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