日期:2014-05-18  浏览次数:20551 次

时间比较


select   *   from   table   where   ...

table有字段cdate,其值形为 "2007-08-01 "

条件是将当前时间所在月,和前一个月,后一个月,共3个月所有满足条件的都查处,这里的条件该怎么写?

------解决方案--------------------
select * from table where cdate between convert(varchar(7),dateadd(m,-1,getdate()),120)+ '-01 ' and convert(varchar(7),dateadd(m,1,getdate()),120)+ '-01 '

不知道可不可以
------解决方案--------------------
--不过最好还是不要对字段cdate进行转换,而是将条件转换成cdate的格式
select * from table
where cdate > = convert(varchar(8), dateadd(month,-1,getdate()), 120)+ '01 '
and cdate < convert(varchar(8), dateadd(month,2,getdate()), 120)+ '01 '
and ...

------解决方案--------------------
select * from [table]
where abs(month(cast(cdate as datetime)) - month(getdate())) < = 1
and year(cast(cdate as datetime))=year(getdate())

------解决方案--------------------
select * from table where ...

table有字段cdate,其值形为 "2007-08-01 "

条件是将当前时间所在月,和前一个月,后一个月,共3个月所有满足条件的都查处,这里的条件该怎么写?

select * from table where abs(month(cast(cdate as datetime)) - month(getdate())) < = 1

要考虑年啊.
select * from table where abs(month(cast(cdate as datetime)) - month(getdate())) < = 1 and year(cdate) = year(getdate())

------解决方案--------------------
楼上的语句去掉 最后 and 一句
应该符合楼主的要求了吧?