Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

ISO Week In SQL Server

From Wiki

Jump to: navigation, search

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

  1. CREATE FUNCTION ISOweek  (@DATE DATETIME)
  2. RETURNS INT
  3. AS
  4. BEGIN
  5.    DECLARE @ISOweek INT
  6.    SET @ISOweek= DATEPART(wk,@DATE)+1
  7.       -DATEPART(wk,CAST(DATEPART(yy,@DATE) AS CHAR(4))+'0104')
  8. --Special cases: Jan 1-3 may belong to the previous year
  9.    IF (@ISOweek=0)
  10.       SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1
  11.          AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1
  12. --Special case: Dec 29-31 may belong to the next year
  13.    IF ((DATEPART(mm,@DATE)=12) AND
  14.       ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))
  15.       SET @ISOweek=1
  16.    RETURN(@ISOweek)
  17. END
  18. GO

Now run the following query on SQL server 2000 and up

  1. 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

  1. 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

595 Rating: 1.0/5 (1 vote cast)