繁体   English   中英

SqL存储过程查找日期,月份和日期

[英]SqL stored procedure to find the dates,month and days

在SQL Server中如何编写查询以获取开始日期和结束日期之间的月份,即月的天数(以月为单位),该月的实际天数

startdate和enddate作为输入参数传递,我需要知道月数,实际天数和该月中的天数

例如:

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-(开始日期从2月2日至12月30日(4月结束))
30-(12月4日的天数)

这是计算一个月中天数的过程。 我不知道您所说的“实际日”是什么意思,或者那可能有什么不同。

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

SQL Fiddle中的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM