Im trying to understand why this code, in my opinion, behaves inconsistently. I have a simple if exists clause which tests if a column is present in a table or not.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'COL' and TABLE_NAME = 'TAB')
BEGIN
PRINT 'EXISTS'
SELECT COL FROM TAB
END
ELSE
BEGIN
PRINT 'NOT EXISTS'
END
This executes just fine in case table TAB has the column COL. If the column COL gets dropped from TAB the statement can not be executed stated invalid column. So far so good. Then if i drop the table TAB altogether the statement is executed just fine and printing "NOT EXISTS". I´ve tested it further and it seems as long as the table does not exist and IF EXISTS is evaluated to false you can write whatever you want for example:
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE 1=0)
BEGIN
PRINT 'EXISTS'
SELECT THISISMYFANTASYCOLUMN FROM FANTASYTABLE
END
ELSE
BEGIN
PRINT 'NOT EXISTS'
END
This statement always prints 'NOT EXISTS' and sqlserver is not complaining.
EDIT: To differentiate from the possible duplicate question. I´m not looking for a solution to this problem which is to use dynamic sql. The question is why existing table + invalid columnname raises an error but non existing table with non existing column is valid. Seans example illustrates the different behaviour more clearly than the original posting.