现在的位置: 首页 > 综合 > 正文

SQL SERVER中,条件语句中的子查询语句的语法没有检查

2011年04月15日 ⁄ 综合 ⁄ 共 1104字 ⁄ 字号 评论关闭
create table tb1(id int identity(1,1),name varchar(10),remark varchar(50default '');
create table tb2(xid int identity(1,1),name varchar(10));

insert into tb1(name)
select 'a'
union all select 'b'
union all select 'c'
insert into tb2(name) select 'x'

select * from tb1 where id in(select id from tb2)
select * from tb1 where id in(select xid from tb2)

drop table tb1
drop table tb2;

结果是:
id          name      remark
----------- ---------- --------------------------------------------------
1          a         
2          b         
3          c         

id          name      remark
----------- ---------- --------------------------------------------------
1          a        

从这段脚本执行后,就可以发现问题:
为何select * from tb1 where id in(select id from tb2)在执行的时候不对条件中的子查询语句做语法检查呢?而且默认的等价于1=1呢?

而且,select * from tb1 where id  in(select id from tb2 where id=1)会按照select * from tb1 where id  in(select xid from tb2 where xid=1)来执行,这说明子查询语句的语法没有被检查,但是过滤却起到了作用,这的确是很奇怪的事情。

如果我在敲sql语句的时候误把 select * from tb1 where id in(select xid from tb2)中的select xid敲成select id,那么取出的数据就会有问题(全取出),但是却得不到提示,因为语法检查跳过了。所以,这个在写sql语句的时候,就是一个潜在的泥坑。

据说在oracle中也存在类似的问题,没有试。

大家在写sql脚本时,还是要谨慎啊,因为今天早上我的sql就出现了这样的问题,谨记教训啊。

抱歉!评论已关闭.