I have seen and used various forms of DateAdd and DateDiff to strip time, get to the first day of any month or to move around a date.
I can see that when performing these calculation a pattern often used is as below:
select DATEADD(m, DATEDIFF(m,0,GETDATE() ), 0) as 'Beginning of the month'
I know that 0 inside the DateDiff expression is "1 Jan 1900". It first gets the date difference in MONTHS between the current month and "1 jan 1900". Then adds back the number of months to "1 Jan 1900" and that way it looses the day information and defaults to the 1 of the month.
I have googled and also tried myself using the technique above to find out a way with which I can may be find out the date of when it is the "First Friday of April". The below snippet is not correct but I was hoping there could be something like the below to find the financial week and year:
DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0)
What I eventually need to do is find out all the financial week numbers (and the corresponding financial year) for any given date range.
The first financial week starts from "1st Friday of April". The second week starts from the next Friday and so on.
I understand that a DATE table would serve and be a lot more productive but I would really like to find a way to do this way for now.
I have written a table-valued function that will produce the data set of a calendar but I need to add the below two columns from the logic I have stated above to make it complete:
- FinancialWeekNumber
- FinancialYear
Below is the code I have written so far:
create function [dbo].[MyDailyDateTable]
(@StartDate datetime, @EndDate datetime) returns @DailyDates table (
DailyDatesID int identity,
DailyDate date,
DayNumber int,
DayName varchar(50),
WeekNumber int,
QuaterNumber int,
MonthNumber int,
MonthCalled varchar(50),
YearNumber int
---- FinancialWeekNumber
---- FinancialYear ) AS BEGIN
while (@StartDate <= @EndDate)
begin
insert into @DailyDates
select @StartDate DailyDate
, datename(day, @StartDate) DayNumber
, datename(dw, @StartDate) DayName
, DATEPART(dw, @StartDate) DayOfTheWeek -- Default 1 = Monday is used ("SET DATEFIRST 1")
, datepart(week, @StartDate) WeekNumber
, DATEPART(qq , @StartDate) as QuarterValue
, datepart(month,@StartDate) MonthNumber
, datename(month,@StartDate) MonthCalled
, YEAR(@StartDate) YearNumber
---- FinancialWeekNumber
---- FinancialYear
set @StartDate = dateadd(day, 1 ,@StartDate)
end
return END