2011-06-23 16 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) 

あなたはTABLE1の明示的になるこの資格をするとき、あなたがエラーを取得し

1

列thisColumnDoesntExistInTable1は、それが言うように、#1 TABLE1には存在しません。最初のクエリでは、コンパイラがサブクエリにヒットすると、列にエイリアスがないため、クエリに関係するすべてのテーブルが検索され、1つのテーブルが検索され、そこから使用されます。 2番目のクエリでは、列にエイリアスが設定されているため、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 

だから、あなたが見ることができるあなたが#table2からthisColumnDoesntExistInTable1の値にアクセスしているので、結果ではなく12が表示されます。