2

我的存储过程@FromDate 和@ToDate 中有2 个参数,我想计算出@FromDate 和@ToDate 之间的周数,@FromDate 始终是星期一,而@ToDate 始终是星期日,但日期可能涵盖数周,月等

目前我有 DATEDIFF(WW, @FromDate, @ToDate)

它返回 4 但我希望它在 4 行中返回 1、2、3 和 4 而不仅仅是 1 行。

实现这一目标的最佳方法是什么?

4

2 回答 2

2

如果我做对了:

With T( Number ) as
(
    Select 0 as Number
        union all
    Select Number + 1
        from T
        where Number < DATEDIFF(WW, @FromDate, @ToDate)

)

SELECT NUMBER FROM T WHERE Number>0;

SQLFiddle 演示

于 2013-07-09T11:27:59.417 回答
0
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

SET @StartDate = GETUTCDATE() - 90
SET @EndDate = GETUTCDATE() 

DECLARE @WeekNumber INT

SET @WeekNumber = DATEDIFF(WW, @StartDate, @EndDate) ;

WITH    CTE_WeekNumber ( WeekNumber )

      AS ( SELECT   1
           WHERE    @WeekNumber >= 1
           UNION ALL
           SELECT   WeekNumber + 1
           FROM     CTE_WeekNumber
           WHERE    @WeekNumber >= WeekNumber + 1
         )

SELECT  *
FROM    CTE_WeekNumber
于 2013-07-09T11:28:04.463 回答