@@DATEFIRST returns an integer which defines the first day of a week for the current session. In so doing, 1 is corresponding to Monday, but 7 - to Sunday respectively. I.e. if
To change value of the first day of a week (for a current session), we can use SET DATEFIRST statement. So, if we run the following script
SET DATEFIRST 1;
SELECT @@DATEFIRST;
we'll obtain 1, i.e. week starts with Monday now.
The first-day-of-a-week settings may be changed through the changing of session language. For example, running
SETLANGUAGE us_english;
SELECT @@DATEFIRST;
lead us to 7 (Sunday) once more, as this value is default for U.S. English, whereas choosing German will do Monday to be the first day of a week.
Nevertheless you can change the language parameter and first day of a week simultaneously to obtain, say, English and a week that will start with Monday:
SET DATEFIRST 1;
SETLANGUAGE us_english;
SELECT @@DATEFIRST;
Language settings impact specifically on the string representation of date/time components. Compare these results:
DECLARE @dt DATE = '2012-12-17'; -- December 17, 2012
Conclusion. If you want to have queries that always give correct results for any settings of server or database, you can specify necessary setting parameters for the session in which these queries are executing; or you need to check the values of corresponding parameters (@@DATEFIRST as example) in each such a query.
Îñîáåííîñòè: MSSQL
You can solve this problem (First occurrence of a Monday in January 2013) without use of @@DATEFIRST with aid of method proposed by Itzik Ben-Gan [8]. The idea of the solution is based on the following:
1. January 1, 1900 was a Monday 2. The number of days between two similar days of the week is divisible by seven
It is possible to mention one more way to solve this task without use of @@DATEFIRST. The method is based on comparison of any function DATEPART/DATENAME with the same function taking the date being Monday as parameter. For example, it may be January 1st, 1900 (already mentioned). Then the initial query in this chapter would look like as
SELECT day FROM dat WHERE DATEPART(dw, day) = DATEPART(dw, '19000101');
or as
SELECT day FROM dat WHERE DATENAME(dw, day) = DATENAME(dw, '19000101');