
The DATEFIRST statement sets the first day of the week for the session to a number from 1 through 7. SELECT change the DATEFIRST setting for a session without changing the language setting, use the SET DATEFIRST command. In SQL Server the values for the days of the week are the following:įor example, for us_english language setting your session’s DATEFIRST setting has a default value 7 (it means that Sunday is the first day of the week), and for German it is 1 (Monday is the first day of the week): The results for week number and day of the week depend on your language settings. SELECT DATEADD(wk, 2, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -last day next week HEDMON did try that, and found (from his comments) that dates from forward responded quickly. SELECT DATEADD(wk, 1, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -last day current week Since his test date and his production dates were different, it seemed like it might be possible that there was a selectivity issue with the dates that SQL could return the data much faster with a more recent date than with an older one. SELECT DATEADD(wk, 0, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -last day previous week SELECT DATEADD(wk, 1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -first day next week SELECT OrderId, DATEADD (day,2,OrderDate) AS OrderPayDate FROM Orders. SELECT DATEADD(wk, 0, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -first day current week Please note that the SQL Server date table with time details in different examples use the basic structure of SQL numbers table and SQL Server DATEADD datetime function.
#SQL SERVER DATEADD CODE#
SELECT DATEADD(wk, -1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) -first day previous week You will see that the following sql samples use SQL Server numbers table code in order to create a periodic time blocks or time intervals for different purposes. Dialogas Demonas Taikintojas SQL Server: group by and DATEADD confusion - Stack Overflow Aptikta Vidutin Smilkalai SQL Server DATEADD Function By. Applies to: SQL Server (all supported versions) Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics Analytics Platform System (PDW) This function adds a specified number value (as a signed integer) to a specified datepart of an input date value, and then returns that modified value.

To get the first or the last day of the week in SQL Server, you can use the following code:
