索引对查询条件顺序的影响

原帖地址:
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=207897

环境:Sql Server2000 +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 时发生语法错误。

--*/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值