Declare @Year Int, @Month Int, @DayName Varchar(25), @NthDay Int
Select @Year = 2012 /*YEAR you want to perform*/
Select @Month = 8 /*MONTH you want to perform*/
Select @DayName = 'Saturday' /*WEEKDAY you want to perform*/
Select @NthDay = 3 /*Nth WEEKDAY you want to perform*/
;With CTEs
As
(
Select 0 Slno
Union All
Select Slno + 1 From CTEs Where Slno <=30
),[Days]
As
(
Select DateName(Weekday,DATEADD(Day,Slno,Cast(@Year as varchar)+ '-' + Cast(@Month as varchar) + '-01')) [Day], DATEADD(Day,Slno,Cast(@Year as varchar)+ '-' + Cast(@Month as varchar) + '-01') [Date] From CTEs
),[DayWithSeq]
As
(
Select ROW_NUMBER() Over(Order By [Date]) Nth,* from [Days] Where Month([Date]) =@Month And [Day] = @DayName
)
Select [Day], [Date] from [DayWithSeq] Where Nth = @NthDay
/*Result*/
Select @Year = 2012 /*YEAR you want to perform*/
Select @Month = 8 /*MONTH you want to perform*/
Select @DayName = 'Saturday' /*WEEKDAY you want to perform*/
Select @NthDay = 3 /*Nth WEEKDAY you want to perform*/
;With CTEs
As
(
Select 0 Slno
Union All
Select Slno + 1 From CTEs Where Slno <=30
),[Days]
As
(
Select DateName(Weekday,DATEADD(Day,Slno,Cast(@Year as varchar)+ '-' + Cast(@Month as varchar) + '-01')) [Day], DATEADD(Day,Slno,Cast(@Year as varchar)+ '-' + Cast(@Month as varchar) + '-01') [Date] From CTEs
),[DayWithSeq]
As
(
Select ROW_NUMBER() Over(Order By [Date]) Nth,* from [Days] Where Month([Date]) =@Month And [Day] = @DayName
)
Select [Day], [Date] from [DayWithSeq] Where Nth = @NthDay
/*Result*/
Is there any way to get Nth weekday name in range of years(i.e: 2010 to 2012) ?
ReplyDeleteYeah! You can have loop outside and pass assign year to @Year.
Deletevery nice ....
ReplyDelete