读书人

时间比较,该怎么处理

发布时间: 2012-02-01 16:58:19 作者: rapoo

时间比较


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 一句
应该符合楼主的要求了吧?

读书人网 >SQL Server

热点推荐