Skip to content

Instantly share code, notes, and snippets.

@vickyharp
Last active July 3, 2019 22:17
Show Gist options
  • Save vickyharp/b95fef40ed9bee0156fa7e2bba705451 to your computer and use it in GitHub Desktop.
Save vickyharp/b95fef40ed9bee0156fa7e2bba705451 to your computer and use it in GitHub Desktop.
TSQL Roman Numeral Converter
declare @numeral varchar(10)
set @numeral = 'MCMXIV'
declare @lookup table(c char(1),v smallint)
insert into @lookup
select 'M',1000 union all
select 'D',500 union all
select 'C',100 union all
select 'L',50 union all
select 'X',10 union all
select 'V',5 union all
select 'I',1
set @numeral = upper(@numeral)
;with numeral(num,i)
as
(
select reverse(@numeral), cast(0 as int)
union all
select
reverse(left(reverse(num),len(num) - 1)),
i +
case
when i < 3 and v < 3 then v
when i <= v then v
when i > v then v * -1
else 0
end
from numeral
inner join @lookup
on left(num,1) = c
where len(num) >= 1
)
select i from numeral where len(num) = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment