-1

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

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

Select * from Dbo.function_name('Oct 03, 2013', 'Nov 21, 2013')

它必须像这样返回日历表。

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
4

2 回答 2

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

于 2013-10-04T23:18:06.360 回答
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'))
于 2013-12-26T07:22:58.023 回答