heartstill

博客园 首页 新随笔 联系 订阅 管理

sql如何取某年某月的第一天和最后一天

SELECT CAST((LEFT('20093',4)+'-'+SUBSTRING('20093',5,LEN('20093'))+'-'+'01') AS DATETIME)
--第一天
SELECT DATEADD(DAY,-1,DATEADD(MONTH,1,CAST((LEFT('20093',4)+'-'+SUBSTRING('20093',5,LEN('20093'))+'-'+'01') AS DATETIME)))
--最后一天

原理:第一天肯定是1号拉 ,最后一天是下个月第一天减一天

 

 

【数据所在服务器】本月的第一天和最后一天:

SELECT dateadd(ms,-1,DATEADD(mm, DATEDIFF(m,0,getdate()), 0)) as mouthfirstdate,dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as mouthlastdate

===============================最后一天=====================================

本月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as mouthlastdate

 下月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+2, 0)) as mouthlastdate

 下下月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+3, 0)) as mouthlastdate

下下下月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+4, 0)) as mouthlastdate

下下下月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+5, 0)) as mouthlastdate

下下下下月【数据所在服务器】最后一天:

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+6, 0)) as mouthlastdate

 ===============================第一天=====================================

本月第一天

SELECT dateadd(ms,-1,DATEADD(mm, DATEDIFF(m,0,getdate()), 0)) as mouthlastdate

下月第一天:

SELECT dateadd(ms,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as mouthlastdate

下下月第一天:

SELECT dateadd(ms,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+2, 0)) as mouthlastdate

 

posted on 2011-09-14 10:34  开始测试  阅读(1323)  评论(0编辑  收藏  举报