The DATEPART function returns a week number according to its week definition. I choose that convention before using calendar logic.

I plan blog ideas in a calendar, usually one week at a time. Readers asked how I organized daily posts. The week number and its first and last dates helped that planning.
DECLARE @Date date = '20160904';
DECLARE @OriginalDateFirst int = @@DATEFIRST;
SET DATEFIRST 7; -- Sunday starts this demonstration week.
SELECT DATEPART(week, @Date) AS WeekOfYear,
CONVERT(char(10), DATEADD(day, 1 - DATEPART(weekday, @Date), @Date), 111) AS FirstDateOfWeek,
CONVERT(char(10), DATEADD(day, 7 - DATEPART(weekday, @Date), @Date), 111) AS LastDateOfWeek,
DATEPART(iso_week, @Date) AS ISOWeekNumber;
SET DATEFIRST @OriginalDateFirst;The example deliberately uses a fixed date and a Sunday-based week. Replace @Date with CONVERT(date, SYSDATETIME()) for the current server date. Saving and restoring DATEFIRST avoids leaving this demonstration setting behind in the connection. Style 111 displays dates as yyyy/mm/dd.

DATEPART(week) places January 1 in week 1 and depends on DATEFIRST. DATEPART(iso_week) uses ISO rules. An ISO week can belong to a neighboring ISO year. The ordinary calendar year doesn’t always supply its correct year label.
The date type and SYSDATETIME require SQL Server 2008 or later. CONVERT formatting doesn’t remove that requirement. Decide whether your application needs Sunday-based, Monday-based or ISO weeks.
Reference: DATEPART week and ISO week rules.
A week number is not a complete calendar label, it is a value that needs its week and year convention.
Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.
Discover more from SQL Authority with Pinal Dave
Subscribe to get the latest posts sent to your email.





5 Comments. Leave new
As you mentioned, you have used CONVERT instead of DATE datatype because DATE datatype not available in previous version of SQL server (i.e. 2005 or earlier),
but still this query cannot work in all versions because SYSDATETIME is also not available in SQL server 2005.
Very true. I think for everybody who is using SQL Server 2005, I should have a new query which uses GETDATE() instead of SYSDATETIME()
thanks
Love your Blog! I get great and useful info from it. Thank you!
THIS IS ABOSLUTLY FUNCTIONAL … THX FOLKS …