Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sqlparser/10102366 to your computer and use it in GitHub Desktop.
Save sqlparser/10102366 to your computer and use it in GitHub Desktop.
blank lines vertical spacing generic rule
CREATE FUNCTION dbo.isoweek (@DATE datetime)
RETURNS INT
WITH EXECUTE AS caller
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))+ 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment