2011-06-23 49 views
2

當運行以下SQL時,您不會在SQL版本2005或2008 R2中發生錯誤。爲什麼T-SQL沒有錯誤?

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 * 
from #table2 
where thisColumnDoesntExistInTable1 in 
(
    select a.thisColumnDoesntExistInTable1 from #table1 a 
) 

...你得到一個錯誤。

回答

4

實際上,你有這個。因此,沒有錯誤

select * from #table2 t2 
where thisColumnDoesntExistInTable1 in 
     (select t2.thisColumnDoesntExistInTable1 from #table1) 

當你有資格這是明確的表1,你的錯誤

1

列thisColumnDoesntExistInTable1沒有,因爲它說,存在於表1#。在第一個查詢中,當編譯器擊中子查詢時,由於該列沒有別名,因此它在查詢中涉及的所有表中查找,在一個查找中查找,然後從中使用它。在第二個查詢中,該列是別名,所以SQL僅檢查列的引用表,沒有找到它並拋出錯誤。

2

查詢的範圍在子選擇中可用。如果您更改#table2中的內容,則可以更清楚地看到這一點。

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 

所以你可以看到,結果將顯示2而不是1,因爲你從#table2訪問的thisColumnDoesntExistInTable1值。

相關問題