1.Dateadd 和 Date diff 经常混合使用
Dateadd(year/month/day,n,指定日期)
Datediff(year/month/day,start_date,end_date)
求某年/某月的第一天
Select dateadd(year/month,
datediff(year/month,’20000101’,getdate()),’20000101’);
20000101作为锚点日期,是以某年某月的第一天
求某年/某月的最后一天
Select dateadd(year/month,
datediff(year/month,’19991231’,getdate()),’19991231’);
19991231作为锚点日期,是以某年某月的最后一天
2.YEAR,MONTH,DAY
分别返回指定日期的年、月、日
过滤日期范围(比如整年或正月),比较自然的方法使用year函数和month函数
例
查询返回2008年生成的所有订单
select orderid,custid,orderdate
from sales.orders
where year(orderdate)=2008;
但是在大多数情况下,当对过滤条件中的列进行一定的处理后就不能有效的使用索引。为了潜在的使用索引,需要对上面的语句中的谓词进行调整
where orderdate>=‘20080101’ and orderdate<‘20090101’;
这样的处理还可以使用可能的索引列orderdate。