给定CREATE FUNCTION
文档中适当的 ISO 周函数(对其中的所有坏习惯进行了一些调整,恕我直言):
CREATE FUNCTION dbo.ISOWeek
(
@dt SMALLDATETIME
)
RETURNS TINYINT
AS
BEGIN
DECLARE @ISOweek TINYINT;
SET @ISOweek = DATEPART(WEEK, @dt) + 1
-DATEPART(WEEK, RTRIM(YEAR(@dt)) + '0104');
IF @ISOweek = 0
BEGIN
SET @ISOweek = dbo.ISOweek
(
RTRIM(YEAR(@dt)-1)+'12'+RTRIM(24 + DAY(@dt))
) + 1;
END
IF MONTH(@dt) = 12 AND DAY(@dt) - DATEPART(DAYOFWEEK, @dt) >= 28
BEGIN
SET @ISOweek = 1;
END
RETURN(@ISOweek);
END
GO
我们可以像这样创建一个表:
CREATE TABLE dbo.ISOWeekCalendar
(
[Date] SMALLDATETIME PRIMARY KEY,
ISOWeekNumber TINYINT,
[Year] INT,
ISOWeek CHAR(8)
);
CREATE UNIQUE INDEX iw ON dbo.ISOWeekCalendar(ISOWeek);
我们可以用任何年份的数据填充它,这使用 2000 - 2029 年的 ISO 周 1-52:
DECLARE @StartDate SMALLDATETIME,
@EndDate SMALLDATETIME;
SELECT @StartDate = '20000102',
@EndDate = '20291229';
INSERT dbo.ISOWeekCalendar([Date])
SELECT TOP (DATEDIFF(DAY, @StartDate, @EndDate)+1) n
= DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY s1.[object_id])-1, @StartDate)
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
ORDER BY s1.[object_id];
现在我们可以更新数据了。
-- delete all non-Mondays:
SET DATEFIRST 1;
DELETE dbo.ISOWeekCalendar WHERE DATEPART(WEEKDAY, [Date]) <> 1;
-- put the proper ISO week number:
UPDATE dbo.ISOWeekCalendar SET ISOWeekNumber = dbo.ISOWeek([Date]);
-- put the year:
UPDATE dbo.ISOWeekCalendar SET [Year] = DATEPART(YEAR, [Date]);
-- update to the correct year for fringe days:
UPDATE dbo.ISOWeekCalendar SET [Year] = [Year] + 1
WHERE ISOWeekNumber = 1 AND MONTH([Date]) = 12;
-- finally, build the calculated value for YYYY-W##:
UPDATE dbo.ISOWeekCalendar
SET ISOWeek = RTRIM([Year]) + '-W' + RIGHT('0' + RTRIM(ISOWeekNumber), 2);
请注意,上述操作只需执行一次。现在我们可以根据输入运行一个非常简单的查询:
SELECT [Date] FROM dbo.ISOWeekCalendar WHERE ISOWeek = '2012-W02';
结果:
Date
-------------------
2012-01-09 00:00:00
我们甚至可以创建一个函数来执行此操作:
CREATE FUNCTION dbo.ISOWeekDate(@ISOWeek CHAR(8))
RETURNS SMALLDATETIME
WITH SCHEMABINDING
AS
BEGIN
RETURN (SELECT [Date] FROM dbo.ISOWeekCalendar
WHERE ISOWeek = @ISOWeek);
END
GO
还有一个相反的功能:
CREATE FUNCTION dbo.ISOWeekFromDate(@Date SMALLDATETIME)
RETURNS CHAR(8)
WITH SCHEMABINDING
AS
BEGIN
RETURN (SELECT TOP (1) ISOWeek FROM dbo.ISOWeekCalendar
WHERE [Date] <= @Date
ORDER BY [Date] DESC);
END
GO
询问:
SELECT dbo.ISOWeekDate('2012-W02'), dbo.ISOWeekFromDate('20120110');
结果:
------------------- --------
2012-01-09 00:00:00 2012-W02
是的,它比复杂的查询需要更多的前期工作,但我更喜欢易用性和更清晰的查询语义。