T-SQL函数生成日历表

时间:2013-10-04 22:10:47

标签: sql sql-server-2008

我需要使用两个返回表的传入参数来创建用户定义的函数。 第一个参数@start日期类型。 第二个参数@end Date type。

没有任何应用程序来生成它。我只需要SQL服务器中的结果。我正在寻找一个简单的T-SQL解决方案。 SQL 2012适合我。

从Dbo.function_name选择*('2013年10月3日','2013年11月21日')

必须像这样返回日历表。

Su  Mo  Tu  We  Th  Fr  Sa
                3   4   5
6   7   8   9   10  11  12
13  14  15  16  17  18  19
20  21  22  23  24  25  26
27  28  29  30  31  1   2
3   4   5   6   7   8   9
10  11  12  13  14  15  16
17  18  19  20  21

2 个答案:

答案 0 :(得分:1)

没有简单的解决方案。把它作为一个挑战来做(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

添加了一个副本

答案 1 :(得分:0)

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
GO

select * from GenerateCalendar ('2013-10-12',DATEADD (MONTH,1,'2013-10-12'))