如果某个表不存在,如果某个列在表上不存在而引发错误之前,为什么MS Sql Server会引发错误?

Bil*_*rry 4 sql-server sql-server-2008

为什么MS Sql Server(2005和2008;其他地方未经测试)如果表中不存在列,如果表不存在则会引发错误,则会引发错误?

更具体地说,我有以下架构(高度减少以显示一切重要):

CREATE TABLE table1 (
id int identity(1,1) primary key
)
Run Code Online (Sandbox Code Playgroud)

为什么以下查询失败并显示错误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
Run Code Online (Sandbox Code Playgroud)

我希望它可能会因多个错误而失败(如果它实际编译并注意到表和列不在那里)或者没有错误(如果它忽略了if语句的内容,因为它们不会跑).我该怎么做让它运行没有错误?

PS实际查询在if语句中有这个但它没有任何区别:

exists (select * from [INFORMATION_SCHEMA].[COLUMNS] t where t.[TABLE_NAME] = 'table1' and t.[COLUMN_NAME] = 'iDoNotExist')
Run Code Online (Sandbox Code Playgroud)

Joe*_*lli 7

您正在看到表的延迟名称解析的影响.