首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

比较日期,请教哪种方法比较好

2012-01-15 
比较日期,请问哪种方法比较好?数据库中有一datetime类型的字段dt,经常要用这个字段来查询(如按年,按月,按

比较日期,请问哪种方法比较好?
数据库中有一datetime类型的字段dt,经常要用这个字段来查询(如按年,按月,按周)等.
如查询7月,据我所知,有如下几种方法,请问哪种好一些?还有没有其它方法?
1:where   year(dt)=2007   and   month(dt)=7
2:where   convert(nvarhcar(7),dt,23)= '2007-7 '
3:where   dt> = '2007-7-1 '   and   dt= < '2007-7-31 '
这些是不是都不会用到索引?
还有按月汇总,我是用   group   by   month(dt)   ?
还望达人指点!
谢谢!


[解决办法]
1:where year(dt)=2007 and month(dt)=7
2:where convert(nvarhcar(7),dt,23)= '2007-7 '
3:where dt> = '2007-7-1 ' and dt= < '2007-7-31 '
无论从哪个角度,都只有3是最好的,不过好像应该这么写
where dt> = '2007-7-1 ' and dt < '2007-8-1 '
[解决办法]
3是会用到索引的

按月汇总,可以用 group by month(dt)

热点排行
Bad Request.