我正在寻找在SQL Server 2008数据库中填充日期维度表的方法。表中的字段如下:
[DateId] INT IDENTITY(1,1) PRIMARY KEY
[DateTime] DATETIME
[Date] DATE
[DayOfWeek_Number] TINYINT
[DayOfWeek_Name] VARCHAR(9)
[DayOfWeek_ShortName] VARCHAR(3)
[Week_Number] TINYINT
[Fiscal_DayOfMonth] TINYINT
[Fiscal_Month_Number] TINYINT
[Fiscal_Month_Name] VARCHAR(12)
[Fiscal_Month_ShortName] VARCHAR(3)
[Fiscal_Quarter] TINYINT
[Fiscal_Year] INT
[Calendar_DayOfMonth] TINYINT
[Calendar_Month Number] TINYINT
[Calendar_Month_Name] VARCHAR(9)
[Calendar_Month_ShortName] VARCHAR(3)
[Calendar_Quarter] TINYINT
[Calendar_Year] INT
[IsLeapYear] BIT
[IsWeekDay] BIT
[IsWeekend] BIT
[IsWorkday] BIT
[IsHoliday] BIT
[HolidayName] VARCHAR(255)
我编写了一个函数DateListInRange(D1,D2),该函数返回两个参数日期D1和D2之间的所有日期。
即。参数“ 2014-01-01”和“ 2014-01-03”将返回:
2014-01-01
2014-01-02
2014-01-03
我想为DATE_DIM表填充某个范围(即2010-01-01至2020-01-01)内的所有日期。可以使用SQL 2008 DATEPART,DATENAME和YEAR函数填充大多数字段。
财政数据包含更多逻辑,其中某些逻辑相互依赖。例如:财政季度1->财政月必须为1、2或3财政季度2->财政月必须为4、5或6
我可以轻松地编写一个接受特定日期的表值函数,然后输出所有财务数据,甚至输出所有字段。然后,我只需要此函数在DateListInRange函数的每一行上运行。
我对速度不是很在意,因为更改假期表后,每年只需要填充几次。
用SQL编写此内容的最佳方法是什么?
目前它是这样的:
SELECT
[Date],
CAST([Date] AS DATE) AS [Date],
DATEPART(W,[Date]) AS [DayOfWeek_Number], -- First day of week is sunday
DATENAME(W,[Date]) AS [DayOfWeek_Name],
SUBSTRING(DATENAME(DW,[Date]),1,3) AS [DayOfWeek_ShortName],
DATEPART(WK, [Date]) AS [WeekNumber],
DATEPART(M, [Date]) AS [Calendar_Month_Number],
DATENAME(M, [Date]) AS [Calendar_Month_Name],
SUBSTRING(DATENAME(M, [Date]),1,3) AS [Calendar_Month_ShortName],
DATEPART(QQ, [Date]) AS [Calendar_Quarter],
YEAR([Date]) AS [Calendar_Year],
CASE WHEN
(
(YEAR([Date]) % 4 = 0) AND (YEAR([Date]) % 100 != 0)
OR
(YEAR([Date]) % 400 = 0)
)
THEN 1 ELSE 0
END AS [IsLeapYear],
CASE WHEN
(
DATEPART(W,[Date]) = 1 OR DATEPART(W,[Date]) = 7
)
THEN 0 ELSE 1
END AS [IsWeekDay]
FROM [DateListForRange]
('2014-01-01','2014-01-31')
如果我对财政数据执行相同的操作,则在每种情况下都会有很多重复,可以避免使用函数,并且可以在日期列表上交叉应用TVF。
请注意,我使用的是SQL Server 2008,因此许多较新的日期功能很少。