是否可以通过给定的周数来获取一周的所有日期,我可以说我从2011年开始提供第2周,并且可以从第一个星期一开始获得所有工作日吗?
答案 0 :(得分: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
尽管如此,最有可能采用更好的方法。