Wednesday, July 11, 2012

DATEFIRST settings side-effect on DATEPART

Upon reading this comment:

DATEPART(DW is dependant upon @@datefirst – Martin Smith Aug 24 '11 at 0:03


I tried this code:


set nocount on;

declare @d date = '2012-07-4';
 
set language italian;
-- SET DATEFIRST 1; -- Italy is Monday-first week. this is equivalent to above
select @@DATEFIRST as df;
select DATEPART(DW, @d) as x;
SELECT DATEADD(ww, DATEDIFF(ww,0,@d), 0) as y;
SELECT DATEADD(DD, 1 - DATEPART(DW, @d), @d) as z;
 
set language us_english;
-- SET DATEFIRST 7; -- US is Sunday-first week. this is equivalent to above
select @@DATEFIRST as df;
select DATEPART(DW, @d) as x;
SELECT DATEADD(ww, DATEDIFF(ww,0,@d), 0) as y;
SELECT DATEADD(DD, 1 - DATEPART(DW, @d), @d) as z;


Output
L'impostazione della lingua è stata sostituita con Italiano.
df
----
1

x
-----------
3

y
-----------------------
2012-07-02 00:00:00.000

z
----------
2012-07-02

Changed language setting to us_english.
df
----
7

x
-----------
4

y
-----------------------
2012-07-02 00:00:00.000

z
----------
2012-07-01

There's a discrepancy(the last queries, z column) when using datepart on obtaining first day of week. On countries(e.g. USA) that start their calendar week with Sunday, the first day of week for July 4, 2012 is July 1, 2012(Sunday). For countries that start their calendar week with Monday, the first day of week for July 4, 2012 is July 2, 2012(Monday).


To avoid this discrepancy, instead of using date functions(e.g. DATEPART) that has a dependency on @@DATEFIRST settings, use date functions that doesn't rely on @@DATEFIRST settings e.g. DATEDIFF

No comments:

Post a Comment