Hi
My problem is second thusday of month how to calculate in sql server
like 2nd thusday .
08/01/2015
12/02/2015
12/03/2015
09/04/2015
14/05/2015
10/06/2015
09/07/2015
13/08/2015
10/09/2015
08/10/2015
12/11/2015
10/12/2015
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Surendra KandiraRank #2,956 · 488 reputationPosted Nov 5, 2015, 3:15 AM EST
select @yearNo=cast(datepart(yy,GETDATE()) as char(4))
select @weekNo={fn week(GETDATE())}
select @weekStart=dateadd(wk,Datediff(wk,6,'1/1/'+@yearNo)+(@weekNo-1),6)
select @weekEnd=dateAdd(wk,datediff(wk,5,'1/1/'+@yearNo)+(@weekNo-1),5)
print @weekStart
print @weekEnd
Upendra Pratap ShahiRank #329 · 7.5K reputationPosted Nov 5, 2015, 7:27 AM EST
Hello,
( monthdate date not null primary key )
insert
into #monthdates ( monthdate )
values
( '2015-11-05' )
, ( '2014-11-06' )
, ( '2013-11-07' )
select monthdate as first_thursday_of_month
, dateadd(day
, ( ( 17 - datepart(dw,monthdate) ) % 7 ) + 7
, monthdate
) as second_thursday_of_month
from #monthdates
drop table #monthdates
Upendra Pratap ShahiRank #329 · 7.5K reputationPosted Nov 5, 2015, 7:30 AM EST
This return for current month-
SELECT
CONVERT(CHAR(10),
DATEADD(wk,1,(CURRENT_TIMESTAMP -
Day(CURRENT_TIMESTAMP)+1)+(5-DATEPART(dw,(CURRENT_TIMESTAMP -
Day(CURRENT_TIMESTAMP)+1)))),
121)
Upendra Pratap ShahiRank #329 · 7.5K reputationPosted Nov 6, 2015, 7:00 AM EST
Surendra KandiraRank #2,956 · 488 reputationPosted Dec 28, 2015, 1:57 AM EST
(
@theDate DATETIME,
@theWeekday TINYINT,
@theNth SMALLINT
)
RETURNS DATETIME
BEGIN
RETURN (
SELECT theDate
FROM (
SELECT DATEADD(DAY, 7 * @theNth - 7 * SIGN(SIGN(@theNth) + 1) +(@theWeekday + 6 - DATEDIFF(DAY, '17530101', DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) % 7) % 7, DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) AS theDate
WHERE @theWeekday BETWEEN 1 AND 7
AND @theNth IN (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5)
) AS d
WHERE DATEDIFF(MONTH, theDate, @theDate) = 0
)
END
Upendra Pratap ShahiRank #329 · 7.5K reputationPosted Jan 6, 2016, 3:12 AM EST
Surendra KandiraRank #2,956 · 488 reputationPosted Feb 20, 2016, 2:31 AM EST