Why does SQL server behave this way. I am running this on SQL 2005.
The IN clause does not validate the column names in the sub query but validates it against the table name in the outer query. Here is an example of getting
Create table #table1(col1 int, col2 char(10), col3 char(15));
Create table #table2(col10 int, col11 char(10), col2 char(15));
insert into #table1(col1, col2, col3)
select 1, 'one', 'three'
insert into #table1(col1, col2, col3)
select 2, 'two', 'three'
insert into #table1(col1, col2, col3)
select 3, 'three', 'four'
insert into #table2(col10, col11, col2)
select 1, 'one', 'three'
insert into #table2(col10, col11, col2)
select 2, 'two', 'three'
insert into #table2(col10, col11, col2)
select 3, 'three', 'four'
select * from #table1
where col1 IN
(select col1 from #table2)
Where as if I just select the "select col1 from #table2" and run it spits an error
Msg 207, Level 16, State 1, Line 1
Invalid column name 'col1'.