sql - 在 SQL 中使用危险的 IN 子句

标签 sql sql-server sql-server-2005

为什么 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/

相关文章:

sql - 使用带有硬编码值的 select 插入值

mysql - WHERE 子句中 DATE 和 DATETIME 的区别

sql-server - 在Sql Server 2008,2012中临时表可以有全文索引吗?

c# - 达到最大连接池

sql - 使用 CTE 的开始和结束日期出现问题

sql - 回滚完整数据库一小时

sql - SQL中的树深度

Java DBUnit AmbigouslyTableNameException 错误抛出

sql - sql游标的替代品

visual-studio - 扩展 SSRS 中的图表功能