没有简单的解决方案。在(whiskyglass.Contents.Any())将其视为挑战后,这就是我得到的......
CREATE FUNCTION dbo.GenerateCalendar
(
@Startdate DATE, @EndDate DATE
)
RETURNS
@Cal TABLE
( Yr INT, Wk INT,Sun DATE, Mon DATE, Tue DATE, Wed DATE, Thu DATE, Fri DATE, Sat DATE)
AS
BEGIN
DECLARE @DaystoBuild int
DECLARE @IntCal TABLE(MonthDate date, Dow INT, YearNum INT , WeekNum int)
SET @DaystoBuild = DATEDIFF(day, @StartDate, @EndDate)
;WITH NumbersTable AS (
SELECT 0 AS number
UNION ALL
SELECT number + 1
FROM NumbersTable
WHERE
number <@DaystoBuild
),
MonthNums (BaseDate,[Index], MonthDate)
AS
(
SELECT @StartDate, number, DATEADD(d, number, @StartDate)
FROM NumbersTable
)
INSERT INTO @IntCal
SELECT MonthDate, DATEPART(weekday, MonthDate) , DATEPART(year, MonthDate), DATEPART(week, MonthDate)
FROM MonthNums
INSERT INTO @Cal
SELECT * FROM @IntCal
PIVOT
( MAX(MonthDate)
FOR Dow IN ( [1],[2],[3],[4],[5],[6],[7])
)AS F ORDER BY 1,2,3
RETURN
END
这不太正确 - 输出是日期而不是整数,并且在年份边界上表现不佳,但对于纯粹的 T-SQL 解决方案可能就足够了。
将副本添加到 SQL Fiddle http://sqlfiddle.com/#!3/98ebe/2