not the most efficient, but works
;with dates as
(select yr,
case mon when 'jan' then 1
when 'feb' then 2
when 'mar' then 3
when 'apr' then 4
when 'may' then 5
when 'jun' then 6
when 'jul' then 7
when 'aug' then 8
when 'sep' then 9
when 'oct' then 10
when 'nov' then 11
when 'dec' then 12
else 99 end as mon,
case dy when 'sun' then 1
when 'mon' then 2
when 'tue' then 3
when 'wed' then 4
when 'thu' then 5
when 'fri' then 6
when 'sat' then 7
else 99 end as dy,
dyno from @tbl),
table2 as (
select *,
CAST (DATEADD(MONTH,d.mon-1, DATEADD(year, d.yr - 1900,'1900/01/01')) as DATE) as month_start,
DATEPART(weekday,DATEADD(MONTH,d.mon-1, DATEADD(year, d.yr - 1900,'1900/01/01'))) as wd
from dates d
), counted as(
select *,
case when (SIGN(dy-wd))>0 then (dy-wd)+7*(dyno-1)
else (dy-wd)+7*(dyno) end as delta
from table2)
select yr,mon,dy,dyno,
case
when mon =99 or dy =99 or DATEDIFF(mm,DATEADD(day,delta,month_start), month_start)<0
then 'Invalid date'
else CAST(DATEADD(day,delta,month_start) as CHAR(10)) end as final
from counted
order by final
Tags: tsql beginner challenge