为什么T-SQL中没有错误?
运行以下SQL时,SQL版本2005或2008 R2中都不会出现错误为什么T-SQL中没有错误?,sql,sql-server-2005,tsql,sql-server-2008,Sql,Sql Server 2005,Tsql,Sql Server 2008,运行以下SQL时,SQL版本2005或2008 R2中都不会出现错误 select 1 as MyVal, 'string' as MyText into #table1 select 1 as thisColumnDoesntExistInTable1, 'string' as MyText into #table2 select * from #table1 select * from #table2 -- WHY NO ERROR HERE --- select * from
select 1 as MyVal, 'string' as MyText
into #table1
select 1 as thisColumnDoesntExistInTable1, 'string' as MyText
into #table2
select * from #table1
select * from #table2
-- WHY NO ERROR HERE ---
select *
from #table2
where thisColumnDoesntExistInTable1 in
(
select thisColumnDoesntExistInTable1 from #table1
)
drop table #table1
drop table #table2
但是如果您通过向内部select添加别名来更改以下语句
select *
from #table2
where thisColumnDoesntExistInTable1 in
(
select a.thisColumnDoesntExistInTable1 from #table1 a
)
…您确实会收到一个错误。实际上,您有这个错误。所以没有错误
select * from #table2 t2
where thisColumnDoesntExistInTable1 in
(select t2.thisColumnDoesntExistInTable1 from #table1 )
当您将其限定为表1中的显式时,您会得到错误列ThisColumnDoesNTESistantable1,正如它所说,不存在于表1中。在第一个查询中,当编译器点击子查询时,因为列没有别名,所以它在查询中涉及的所有表中查找,在一个表中查找,然后从那里使用它。在第二个查询中,列具有别名,因此SQL只检查引用表中的列,没有找到该列,并抛出错误。查询的范围在子选择中可用。如果更改表2中的内容,您可以更清楚地看到这一点 您可以看到,结果将显示2而不是1,因为您正在从表2中访问ThisColumnDoesnTextIsistantable1的值
select 1 as MyVal, 'string' as MyText
into #table1
select 2 as thisColumnDoesntExistInTable1, 'string' as MyText
into #table2
select * from #table1
select * from #table2
select * from #table2 where thisColumnDoesntExistInTable1 in (select thisColumnDoesntExistInTable1 from #table1 )
drop table #table1
drop table #table2