Why does MS Sql Server cause an error if a column does not exist in the table before it causes an error if the table does not exist?

Why does the MS Sql server (2005 and 2008, not verified elsewhere) cause an error if the column does not exist in the table before it causes an error if the table does not exist?

In particular, I have the following scheme (very abbreviated to show everything important):

CREATE TABLE table1 ( id int identity(1,1) primary key ) 

Why the following query failed with an 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 that it will either work with a few errors (as if it really compiled and noticed that the table and column are not there) or there are no errors (as if it ignored the contents of the if statements, since they were not going to work). What can I do to run it without errors?

PS the actual request has this in if statements, but it does not make any difference:

 exists (select * from [INFORMATION_SCHEMA].[COLUMNS] t where t.[TABLE_NAME] = 'table1' and t.[COLUMN_NAME] = 'iDoNotExist') 
+4
source share
2 answers

You see the effect of deferred name resolution for tables.

+7
source

RE:

What can I do to run it without errors?

Use EXEC so that the statement is executed in a child batch that has not been compiled if the IF branch was not taken.

 IF 1 = 2 BEGIN PRINT 'column that shouldn''t exist does' EXEC ('SELECT iDoNotExist FROM table1') END 

Another theoretical possibility is to delay compiling the complaint by adding a No-Op link 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 

It is impossible to imagine any circumstances that would be useful in the preference of EXEC .

+2
source

Source: https://habr.com/ru/post/1382600/


All Articles