Why does MS Sql Server (2005 and 2008; untested elsewhere) raise an error if a column doesn't exist on a table before it raises an error if a table doesn't exist?
More specifically I have the following schema (highly reduced to show everything important):
CREATE TABLE table1 (
id int identity(1,1) primary key
)
Why does the following query fail with the error Invalid column name 'iDoNotExist'.
?
if 1=2
begin
print 'table that shouldn''t exist does'
select * from [IDoNotExist]
end
if 1=2
begin
print 'column that shouldn''t exist does'
select iDoNotExist from table1
end
I expect it to either fail with multiple errors (as it would if it actually compiled and noticed that the table and column were not there) or no errors (as it would if it ignored the contents of the if statements since they were not going to run). What can I do to get it to run without errors?
PS the actual query has this in the if statements but it doesn't make any difference:
exists (select * from [INFORMATION_SCHEMA].[COLUMNS] t where t.[TABLE_NAME] = 'table1' and t.[COLUMN_NAME] = 'iDoNotExist')
You're seeing the effect of deferred name resolution for tables.
RE:
What can I do to get it to run without errors?
Use EXEC
so that the statement runs in a child batch not compiled unless the IF
branch is taken.
IF 1 = 2
BEGIN
PRINT 'column that shouldn''t exist does'
EXEC ('SELECT iDoNotExist FROM table1')
END
One other theoretical possibility would be to defer compilation of the offending statement by adding in a No-Op reference to another non existing table.
IF 1 = 2
BEGIN
PRINT 'column that shouldn''t exist does'
CREATE TABLE #T(X INT)
SELECT iDoNotExist
FROM table1, (SELECT MAX(X) X FROM #T) T
DROP TABLE #T
END
Can't imagine any circumstances that would be useful in preference to EXEC
though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With