Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
ISO Week In SQL Server
From Wiki
Sometimes you need to show the ISO week in SQL server but there was no built in way to calculate it until SQL server 2008 was released. In SQL Server 2000/2005 you could use the user defined function ISOweek which was in the SQL Server books on line. Here is what the function looks like
- CREATE FUNCTION ISOweek (@DATE datetime)
- RETURNS int
- AS
- BEGIN
- DECLARE @ISOweek int
- SET @ISOweek= DATEPART(wk,@DATE)+1
- -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104')
- --Special cases: Jan 1-3 may belong to the previous year
- IF (@ISOweek=0)
- SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1
- AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1
- --Special case: Dec 29-31 may belong to the next year
- IF ((DATEPART(mm,@DATE)=12) AND
- ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))
- SET @ISOweek=1
- RETURN(@ISOweek)
- END
- GO
Now run the following query on SQL server 2000 and up
- select dbo.ISOweek('20071231'),datepart(wk,'20071231')
As you can see SQL Server's wk part returns 53 while ISO week returns 1
If you are running SQL server 2008 then you can use DATEPART and the datepart argument isowk. Run the select statement below to see the result
- select datepart(isowk,'20071231'),datepart(wk,'20071231')
As you can see also here SQL Server's wk part returns 53 while isowk returns 1
Contributed by: --SQLDenis 15:57, 22 September 2008 (GMT)
Part of SQL Server Programming Hacks
Section Dates



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.