|
|
|
SSC Veteran
      
Group: General Forum Members
Last Login: Monday, May 13, 2013 7:08 AM
Points: 292,
Visits: 657
|
|
nigel,
That was what I was getting at.
publicdh-tech,
I like your point about 2008. Not being lucky enough to be using (or even testing) 2008 I'd not contemplated you can just use the date.
|
|
|
|
|
Ten Centuries
      
Group: General Forum Members
Last Login: Monday, June 03, 2013 9:46 AM
Points: 1,164,
Visits: 2,603
|
|
gerald.drouin (8/12/2009)
declare @DayToFind tinyint, @AnyDayInAMonth datetime select @DayToFind = 1, --Monday @AnyDayInAMonth = '2009-04-15' --Target month
select dateadd(day, (datepart(d, @AnyDayInAMonth) - datepart(dw, @AnyDayInAMonth) - @@datefirst + @DayToFind) % 7, dateadd(day, 1-datepart(d, @AnyDayInAMonth), @AnyDayInAMonth)) Seems like a nice single-select statement to me.
Gerald,
There are some issues with your solution which you'll see if you set @AnyDayInAMonth to '2009-08-01'. The problem is with the expression:
datepart(d, @AnyDayInAMonth) - datepart(dw, @AnyDayInAMonth) - @@datefirst + @DayToFind
which can yield a negative value in some cases.
But still good to see an attempt using @@DATEFIRST to make the solution universal, without using loops, and without the horrible constant that I had in my solution.
Nigel
-- Nigel Useful Links: How to post data/code on a forum to get the best help The "Numbers" or "Tally" Table - Jeff Moden
|
|
|
|
|
SSC-Enthusiastic
      
Group: General Forum Members
Last Login: Today @ 1:33 PM
Points: 176,
Visits: 188
|
|
Thanks for the catch on the negative numbers. I've added a 14 day offset to ensure the code always lands in the current month. Works for every day in 2009 now.
declare @DayToFind tinyint, @AnyDayInAMonth datetime select @DayToFind = 1, --Monday @AnyDayInAMonth = '2009-04-15' --Target month select dateadd(day, (datepart(d, @AnyDayInAMonth) - datepart(dw, @AnyDayInAMonth) - @@datefirst + @DayToFind + 14) % 7, dateadd(day, 1-datepart(d, @AnyDayInAMonth), @AnyDayInAMonth))
|
|
|
|
|
Ten Centuries
      
Group: General Forum Members
Last Login: Monday, June 03, 2013 9:46 AM
Points: 1,164,
Visits: 2,603
|
|
gerald.drouin (8/13/2009)
Thanks for the catch on the negative numbers. I've added a 14 day offset to ensure the code always lands in the current month. Works for every day in 2009 now. declare @DayToFind tinyint, @AnyDayInAMonth datetime select @DayToFind = 1, --Monday @AnyDayInAMonth = '2009-04-15' --Target month select dateadd(day, (datepart(d, @AnyDayInAMonth) - datepart(dw, @AnyDayInAMonth) - @@datefirst + @DayToFind + 14) % 7, dateadd(day, 1-datepart(d, @AnyDayInAMonth), @AnyDayInAMonth))
Gerald,
Yep, hopefully that does it. Was hoping to come up with a solution without that pesky constant but I've yet to find it. No doubt someone will, given the level of expertise here.
Nigel
-- Nigel Useful Links: How to post data/code on a forum to get the best help The "Numbers" or "Tally" Table - Jeff Moden
|
|
|
|