为什么 SQL Server 会这样。我在 SQL 2005 上运行它。
IN 子句不验证子查询中的列名,而是验证它
针对外部查询中的表名。这是获取的示例
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)
好像我只是选择“select col1 from #table2”并运行它会吐出一个错误
Msg 207, Level 16, State 1, Line 1
Invalid column name 'col1'.
最佳答案
为什么?因为能够在子查询中从外部查询中引用列通常很有用。没有可用于关闭此行为的设置,但如果您养成使用别名的习惯,则应避免大多数问题:
select * from #table1 t1
where t1.col1 IN
(select t2.col1 from #table2 t2)
会产生错误。
关于sql - 在 SQL 中使用危险的 IN 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12319185/