is there a way in SQL that I can calculate the following in a stored procedure using GETDATE() or something similar ?
Also, I am looking for a way to add specific dates to the above list, eg April 1 of the current year.
I hope someone here can help me with this. Many thanks in advance, Tim.
This is where using a Calendar table can come in very handy.
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...
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.