按日期字段的范围查询,如果将2008年12月1日 23点这个日期值算在2008年12月1日中呀.求处理最高效代码
-----------------------------------------------------
注,比如表中存贮的日期值,都是有分秒信息的.但是我的where语句中,不写分时秒信息,我的代码中有注释,大家一看应该就明白我想问的是什么了:
drop table aacreate table aa(
    f1 int,
    fd datetime
)insert into aa
select 1,'2004-1-2' union all
select 11,'1990-2-5' union all
select 12,'2008-3-5' union all
select 71,'2007-5-9' union all
select 72,'2008-12-1 23:59:59.000'set dateformat 'dmy'
--set dateformat 'mdy'select *
from aa
order by fd/*下面我要查出日期范围从2008年1月12日到2008年12月1日的所有记录
    大家可以看到,第72行记录,日期为2008-12-1,虽然是23点了,但是也属于
    12月1日呀,但是用下面的代码却不包含
*/select *
from aa
where fd >='20080112' and fd<='20081201'--结果如下,并不满足我的要求
/*
f1          fd                                                     
----------- ------------------------------------------------------ 
12          2008-03-05 00:00:00.000(所影响的行数为 1 行)
*//*
为了实现我的要求,我只能在日期字段上用函数,如下所示,但是资料上说,对字段加函数是
最影响效率了,可是不加函数,有别的好办法吗?
*/select *
from aa
where convert(char(10),fd,112) >='20080112' and convert(char(10),fd,112)<='20081201'--结果如下,可以满足我的要求,但是不对字段应用函数可以实现吗?/*
f1          fd                                                     
----------- ------------------------------------------------------ 
12          2008-03-05 00:00:00.000
72          2008-12-01 23:59:59.000(所影响的行数为 2 行)
*/

解决方案 »

  1.   

    select *
    from aa
    where fd >='20080112' and fd<dateadd(day,1,'20081201')
      

  2.   

    这个问题的实现,如果对字段用convert函数处理,非常好实现.
    但是据说这样做效率太差,因为记录太多了,有时要在几万条记录中找,速度很重要.
    所以想找高效的处理代码
      

  3.   

    select *
    from aa
    where fd >='20080112' and fd-1<'20081201'
      

  4.   

    fd >='20080112' and fd<'20081202'
      

  5.   

    1、select * from aa where fd >='20080112' and fd-1<'20081201'
    2、select * from aa where fd >='20080112' and fd<dateadd(day,1,'20081201')
    1和2的性能非常接近,都使用了字段FD的索引。
    但1的fd-1在索引下每条需要检索的记录都需要执行一遍,实际是执行fd - '1900-01-02 12:00AM' < '20081201'
      2的dateadd(day,1,'20081201')只是在编译的时候执行一遍,实际是执行 fd <'20081201'
    所以当结果集较大的时候,1的性能略微比2的性能差些,一般情况下可以忽略不计。
      

  6.   

    select * from aa where fd >='20080112' and fd <dateadd(day,1,'20081201') 标准