The problem is that SQL Server wants to compile the entire batch before it runs it.
And it cannot compile the package because the column is missing.
So, you have to make sure that the package can compile without trying to compile the DELETE , so save it as a string and make it compile separately:
IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1') IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1' AND COLUMN_NAME = 'COL1') EXEC sp_executesql 'delete TAB1 where COL1 not in (select COL2 from TAB2);'
You said:
As a programmer, I know that the delete command will not be executed if both condition blocks are false.
Assuming, say, C # background, your original request is like making two reflection calls to determine if a type has a specific property, and then has a line of code that directly uses this property for an object of that type - if the type does not have a property, the code is not going to compile, so reflection checks will never be performed.
source share