Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MS Sql Server raise an error if a column doesn't exist on a table before it raises an error if a table doesn't exist?

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')
like image 572
Bill Barry Avatar asked Jan 18 '23 05:01

Bill Barry


2 Answers

You're seeing the effect of deferred name resolution for tables.

like image 106
Joe Stefanelli Avatar answered Jan 27 '23 04:01

Joe Stefanelli


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.

like image 39
Martin Smith Avatar answered Jan 27 '23 05:01

Martin Smith