Get the Monday date of a given week in a given year
I have not done much sophisticated SQL server programming, generally I profer ad-hoc queries, select-insert-update-delete, and leave other calculations in .net programming. (When I do do heavy-lifting database programming, I use foxpro. I like quick and dirty stuff. Really have to try to pay more attention to style and comments).
However, a user question in DNS forum really got me to look at SQL programmabilities, especially writing native sql functions.
Quoting the user question:
"I'm pretty new to all the SQL Server things, but I was wondering if the following is possible:
@Week=26 and @Year=2008, based on these two variables, is it possible to let SQL Server calculate the date of the monday in week 26?"
Some quick thinking and quick search led me to the following solution of mine.
CREATE FUNCTION [dbo].[GetFirstMondayOfAWeekInYear]
( @InputYear int,
@InputWeekNo int
)
RETURNS DATETIME
BEGIN
declare @firstDayOfYear as datetime, @firstMondayOfYear as datetime;
--get the first day of year
set @firstDayOfYear = convert(VARCHAR(10),str(@InputYear)+ '-1-1',111)
set @firstMondayOfYear = DATEADD(DD, 1 - DATEPART(DW, @firstDayOfYear)+1,
@firstDayOfYear);
RETURN DATEADD(DD, (@InputWeekNo -1) * 7, @firstMondayOfYear)
END
GO
To use the function, you just call:
select
dbo.GetFirstMondayOfAWeekInYear(2008, 26)
I tested, it worked like charm.
Action steps in the function
1) Get the date of the first day of the given year. Easy, the first date of any year would be Year + "-1-1".
2) Find out the date of the monday of this week. For example, for 2008, the first monday date would be 12-31-2007.
3) Now, add #weeks * 7 to the very first monday, there we get it.