Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- declare @i varchar(999) = '3 1 1 1970 20 7 1988 12 12 2012';
- ;with parseinput as
- (
- select n = cast(substring(@i,1,charindex(' ',@i)-1) as int)*3,
- i = cast(substring(@i,charindex(' ',@i)+1,999)+' ' as varchar(100)),
- x = 0,
- t = 'x'
- union all
- select n = n-1,
- i = cast(substring(i,charindex(' ',i)+1,999) as varchar(100)),
- x = cast(substring(i,1,charindex(' ',i)-1) as int),
- t = case n%3 when 0 then 'd' when 2 then 'm' else 'y' end
- from parseinput
- where n > 0
- )
- ,pivotdates as
- (
- select n = n/3,
- d = max(case when t = 'd' then x else 0 end),
- m = max(case when t = 'm' then x else 0 end),
- y = max(case when t = 'y' then x else 0 end)
- from parseinput
- where t <> 'x'
- group by n/3
- )
- ,leapyears as
- (
- select 1972 as yr
- union all
- select yr+case when (yr+4) % 100 = 0 and (yr+4) % 400 <> 0 then 8 else 4 end
- from leapyears
- where yr < 100000
- )
- ,datediffs as
- (
- select n,
- midx = 1856304
- + (y-1970)*365
- + case m when 1 then 0 when 5 then 120 when 9 then 243
- when 2 then 31 when 6 then 151 when 10 then 273
- when 3 then 59 when 7 then 181 when 11 then 304
- when 4 then 90 when 8 then 212 when 12 then 334
- end
- + (d)
- + ( select count(*) from leapyears where yr<y or (yr=y and m>2) )
- from pivotdates
- )
- ,convertmayan as
- (
- select n,
- baktun = cast(midx/20/20/18/20 as varchar(9)),
- katun = cast(midx/20/18/20 % 20 as varchar(9)),
- tun = cast(midx/20/18 % 20 as varchar(9)),
- winal = cast(midx/20 % 18 as varchar(9)),
- kin = cast(midx % 20 as varchar(9))
- from datediffs
- )
- select baktun+'.'+katun+'.'+tun+'.'+winal+'.'+kin
- from convertmayan
- order by n desc
- option (maxrecursion 32000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement