(I apologize in advance for the terrible explanation, but if you run the queries below, you'll see what I mean!)
Why does MSSQL evaluate statements in the true section of the if exists construct, even if if exists returns false, causing errors?
For example, in the two queries below, the first checks if the table exists (what it does), and also checks if there are certain columns in this table. For some reason, running this query causes the following errors because the table exists but the columns do not.
Msg 207, Level 16, State 1, Line 21 Invalid column name 'colB'. Msg 207, Level 16, State 1, Line 21 Invalid column name 'colC'. Msg 207, Level 16, State 1, Line 21 Invalid column name 'colA'.
The behavior I was expecting here was that SQL simply moved to the falsepart construct without causing errors. (As with the next request).
However, the second script (which is identical, the names of the table tables) is successful. This is because the table the query is looking for does not exist.
--Scripts to setup the example. CREATE DATABASE TEST GO USE TEST GO CREATE TABLE t1 (colD VARCHAR(255)) --Create a table with the correct name, but incorrect column names. GO --This query fails, because t1 exists, even though the columns in t1 don't. IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 't1' AND COLUMN_NAME IN ('colA','colB','colC')) BEGIN SELECT colA FROM t1 WHERE colB = 0 AND colC = 1 END ELSE BEGIN SELECT 'FALSE' END GO --This query executes ok, because t2 does not exist. IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 't2' AND COLUMN_NAME IN ('colA','colB','colC')) BEGIN SELECT colA FROM t2 WHERE colB = 0 AND colC = 1 END ELSE BEGIN SELECT 'FALSE' END
Can someone explain to me why the first request errors when the second request is working fine?
So far, I have only been able to verify this in Microsoft SQL Server 2012.