2012-10-10 49 views
1

在SQL Server中如何编写查询以获取startdate和enddate之间的月份,本月的月份(以月为单位),本月的实际天数SqL存储过程查找日期,月份和日期

开始日期和结束日期作为输入参数传递,我需要知道几个月,实际的天数和天数的月份数

如:

Start date : 2012-04-02 
End date : 2012-08-23 

我需要得到结果为,

Month  Days  ActualDays _ inMonth  
---------------------------------------------- 
04   29  30 - (The no of days on Apr'12) 
05   31  31  
06   31  31  
07   31  31  
08   31  31 

04个月的
29日 - (FRM STARTDATE 2 - 4月至至30 Apr'12(4月完))
30 - (否的上Apr'12天)

+0

提示:加*请help..very迫切*通常不会帮助你的问题,有时会伤害它 – RedFilter

+1

如果什么日期跨越新的一年?你的输出不会告诉你一个月的哪一年... – RedFilter

+0

[你有什么试过](http://whathaveyoutried.com)? – HABO

回答

1

这里有一个程序来计算一个月内的天数。我不知道你的意思是“实际的日子”,或者说这可能是不同的。

if object_id('spMonthList') is not null 
    drop procedure spMonthList 
go 
create procedure dbo.spMonthList(
    @start date 
, @end date) 
as 
; with Months as 
     (
     select dateadd(month, datediff(month, 0, @start), 0) as MonthStart 
     union all 
     select dateadd(month, 1, MonthStart) 
     from Months 
     where MonthStart < @end 
     ) 
select datepart(month, MonthStart) as Month 
,  datediff(day, MonthStart, dateadd(month, 1, MonthStart)) as NumberOfDays 
from Months; 
go 
exec spMonthList '2012-04-01', '2012-08-01' 

- >

Month NumberOfDays 
4  30 
5  31 
6  30 
7  31 
8  31 

Example at SQL Fiddle.