FIRSTWEEKDAY
Updated 2023-10-06 23:53:59.080000
Syntax
SELECT [westclintech].[wct].[FIRSTWEEKDAY](
<@StartDate, datetime,>
,<@DayofWeek, nvarchar(4000),>)
Description
Use the scalar function FIRSTWEEKDAY to return the first specified day of the week in any calendar month.
Arguments
@DayofWeek
the day of the week to be returned. @DayofWeek can be specified using the numbers 1 – 7, where 1 is Sunday and 7 is Saturday, or by using the name of the day of the week (e.g. 'Monday') or the abbreviated name of the week (e.g. 'Mon') as controlled by the Windows Regional Settings on the Windows Server.
@StartDate
specifies the month and year of the return value. FIRSTWEEKDAY returns the first @DayofWeek in the month and year of @StartDate. @StartDate is an expression of type datetime or of a type that can be implicitly converted to datetime.
Return Type
float
Remarks
@StartDate must be a valid date.
@StartDate only determines the month and year of the returned value.
@DayofWeek always understands 1 to mean Sunday and 7 to mean Saturday. The day of week name and abbreviated name are validated against the Windows Server Regional Settings and not the SQL Server language settings.
Use the LASTWEEKDAY function to calculate the last specified day of the week in any calendar month.
Examples
In this example we calculate the first Wednesday in January 2013.
SELECT wct.FIRSTWEEKDAY('2013-01-01', 4) as [First Wednesday];
This produces the following result.
{"columns":[{"field":"First Wednesday","headerClass":"ag-right-aligned-header","cellClass":"ag-right-aligned-cell"}],"rows":[{"First Wednesday":"2013-01-02 00:00:00.000"}]}
If we wanted to calculate the 3rd Wednesday of the month, we can simply add 14 days or 2 weeks to the first Wednesday.
SELECT DATEADD(d, 14, wct.FIRSTWEEKDAY('2013-01-01', 'Wednesday')) as [Third Wednesday]
UNION
SELECT DATEADD(ww, 2, wct.FIRSTWEEKDAY('2013-01-01', 'Wednesday'));
This produces the following result.
{"columns":[{"field":"Third Wednesday","headerClass":"ag-right-aligned-header","cellClass":"ag-right-aligned-cell"}],"rows":[{"Third Wednesday":"2013-01-16 00:00:00.000"}]}
See Also
BUSDAYS - Calculate the number of business days between two dates
BUSINESSDATE - Calculate a Business Date from an offset
BUSINESSDATEWE - Calculate a Business Date from an offset and specified weekend days
LASTWEEKDAY - Calculate the first occurrence of a weekday in a given month
NETWORKDAYS - Calculate the number of working days between two dates (inclusive)
YEARFRAC - Calculate the difference between two dates as a fraction of a year