Created
July 1, 2015 15:22
-
-
Save ststeiger/696729c26c87f73e5de1 to your computer and use it in GitHub Desktop.
Get ISO-Week and year string from date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_get_ISOWeek]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) | |
| DROP FUNCTION [dbo].[fu_get_ISOWeek] | |
| GO | |
| -- PRE: Valid datetime | |
| -- POST: ISO week number + '/' + year, NULL on NULL | |
| CREATE FUNCTION [dbo].[fu_get_ISOWeek](@dtDate as DATETIME) | |
| RETURNS nvarchar(7) WITH RETURNS NULL ON NULL INPUT | |
| AS | |
| BEGIN | |
| DECLARE @intISOWeekNumber int | |
| ,@intYear int | |
| SET @intISOWeekNumber = DATEPART(ISO_WEEK, @dtDate) | |
| IF (DATEPART(mm, @dtDate) = 1 AND @intISOWeekNumber > 50) | |
| SET @intYear = DATEPART(yyyy, @dtDate)- 1 | |
| ELSE IF (DATEPART(mm, @dtDate) = 12 AND @intISOWeekNumber = 1) | |
| SET @intYear = DATEPART(yyyy, @dtDate) + 1 | |
| ELSE | |
| SET @intYear = DATEPART(yyyy, @dtDate) | |
| RETURN (CAST(@intISOWeekNumber AS nvarchar) + '/' + CAST(@intYear AS nvarchar)) | |
| END | |
| GO | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment