1

是否可以通过给定的周数获取一周的所有日期,假设我提供了 2011 年的第 2 周,我可以从第一个 monda 开始获得所有的工作日吗?

4

1 回答 1

2

这可能有效:

SET DATEFIRST 1
DECLARE @wk int SET @wk = 2
DECLARE @yr int SET @yr = 2011

--define start and end limits
DECLARE @todate datetime, @fromdate datetime
SELECT @fromdate = dateadd (week, @wk, dateadd (YEAR, @yr-1900, 0)) - 4 -
         datepart(dw, dateadd (week, @wk, dateadd (YEAR, @yr-1900, 0)) - 4) + 1
SELECT @todate = @fromdate + 6

;WITH DateSequence( Date ) AS
(
    SELECT @fromdate AS Date
        UNION ALL
    SELECT dateadd(DAY, 1, Date)
        FROM DateSequence
        WHERE Date < @todate
)

--select result
SELECT * FROM DateSequence OPTION (MaxRecursion 1000)

它在互联网上发现的点点滴滴上进行了修补,并将生成以下结果:

Date
-----------------------
2011-01-10 00:00:00.000
2011-01-11 00:00:00.000
2011-01-12 00:00:00.000
2011-01-13 00:00:00.000
2011-01-14 00:00:00.000
2011-01-15 00:00:00.000
2011-01-16 00:00:00.000

不过,很可能有更好的方法来做到这一点。

于 2013-11-11T16:57:58.157 回答