Question

is there a way in SQL that I can calculate the following in a stored procedure using GETDATE() or something similar ?

  • First Monday in March of current year
  • Last Monday in May of current year
  • Third Friday in October of current year

Also, I am looking for a way to add specific dates to the above list, e.g. April 1 of the current year.

I hope someone here can help me with this. Many thanks in advance, Tim.

Was it helpful?

Solution

It is possible to calculate it, here are 3 examples

declare @month int = 6

select 
    -- first Monday in @month of current year
    dateadd(d, datediff(d, 0, dateadd(m, @month-1, 
      dateadd(yy, datediff(yy, 0, getdate()), 6)))/7*7, 0),
    -- last Monday in @month of current year
    dateadd(d, datediff(d, 0, dateadd(m, @month, 
      dateadd(yy, datediff(yy, 0, getdate()), 6)))/7*7, -7),
    -- third Friday in @month of current year
    dateadd(d, datediff(d, 0, dateadd(m, @month-1, 
      dateadd(yy, datediff(yy, 0, getdate()), 3)))/7*7, 18)

OTHER TIPS

This is where using a Calendar table can come in very handy.

http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html

You can then simply join to the table to determine what you are looking for.

For example, finding the first monday in march of the current year:

SELECT TOP 1 dt 
  FROM dbo.CALENDAR 
 WHERE Y = @currentyear and M = 3 and DW = 2 
 ORDER by dt

For more complex things, you can use ROW_NUMBER() and ordering to figure out the "third friday", etc...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top