实例讲解索引对查询条件顺序的具体影响

上一篇 / 下一篇  2007-12-25 09:45:00 / 个人分类:数据天地

 

这篇文章根据具体的实例着重的讲解了索引对查询条件顺序所产生的影响,希望下面的具体示例对大家的学习和工作有所帮助。

环境:SQL Server 2000 +sp4

具体问题:

select datediff(day,´20040910´,´20040920´) 
 --此语句可以执行

但下面这句不能执行(有时也可以执行)

--sub_para为varchar(8),错误信息为:从字符串转换为 datetime 时发生语法错误。

select * from T_SUB 
where item_local_code=´03004´ 
 and  datediff(day,sub_para,getdate())=29 
 and (sub_del_flag<>1)

并且在其不能执行时,此语句不会返回任何记录集。

select * from t_sub
where  item_local_code=´03004´ 
 and isDate(sub_para)=0 

---------------------------------------

具体原因:表中创建的索引影响了条件的执行顺序导致先执行了 datediff(day,sub_para,getdate())

以下的的测试说明了这个问题。

测试表和数据:

create table tb(
item_local_code char(5),
sub_del_flag int,
sub_para varchar(10),
constraint PK_t primary key(sub_para,item_local_code)
)
insert tb select ´03004´,1,´2003-1-1´
union all select ´03005´,1,´2003a1-1´
go

--查询语句
select * from (
 select * from tb 
 where item_local_code=´03004´ 
  and sub_del_flag<>0
  and isdate(sub_para)=1
) A where datediff(day,sub_para,getdate())>29
go

--删除测试
drop table tb

/*--测试结果

item_local_code sub_del_flag sub_para   
--------------- ------------ ---------- 
03004           1            2003-1-1

服务器: 消息 241,级别 16,状态 1,行 3
从字符串转换为 datetime 时发生语法错误。

--*/

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-07-30  
  12345
6789101112
13141516171819
20212223242526
2728293031  

数据统计

  • 访问量: 1202
  • 日志数: 90
  • 建立时间: 2007-04-03
  • 更新时间: 2008-04-07

RSS订阅

Open Toolbar