请参阅我上面关于计算第一个月的天数的评论。我假设您要返回从开始日期开始的月份中剩余的天数。这是一个使用测试日期完成此操作的循环:
DECLARE @BeginDate DATE = '1/15/2014',
@EndDate DATE = '3/15/2015',
@CurrentMonth INT = 0
DECLARE @MonthCounter INT = DATEDIFF(Month, @BeginDate, @EndDate) + 1
DECLARE @Results TABLE (DateValue DATE, NumberOfDays INT)
WHILE @CurrentMonth < @MonthCounter
BEGIN
IF @CurrentMonth = 0
BEGIN
INSERT @Results
SELECT DATEADD(MONTH,@CurrentMonth,@BeginDate) AS DateValue,
DAY(EOMONTH(DATEADD(MONTH,@CurrentMonth,@BeginDate))) - DAY(@BeginDate) AS NumberOfDays
END
ELSE IF @CurrentMonth = @MonthCounter - 1
BEGIN
INSERT @Results
SELECT DATEADD(MONTH,@CurrentMonth,@BeginDate) AS DateValue,
DAY(@EndDate) AS NumberOfDays
END
ELSE
BEGIN
INSERT @Results
SELECT DATEADD(MONTH,@CurrentMonth,@BeginDate) AS DateValue,
DAY(EOMONTH(DATEADD(MONTH,@CurrentMonth,@BeginDate))) AS NumberOfDays
END
SET @CurrentMonth = @CurrentMonth + 1
END
SELECT DATENAME(Month,DateValue) + ' ' + CONVERT(VARCHAR(10),YEAR(DateValue)) AS [Month], NumberOfDays
FROM @Results