Today I got assignment to make ms sql function to convert decimal to roman numeral
here’s the code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Function DecToRom ( @InputNumber as varchar(MAX) ) RETURNS varchar(MAX) AS BEGIN DECLARE @Hasil varchar(MAX), @RomanLetter varchar(7), @InputTemp bigint, @Posisi int, @Mod bigint SET @Hasil = '' SET @RomanLetter = 'IVXLCDM' IF @InputNumber = 0 SET @Hasil = '0' ELSE BEGIN SELECT @Posisi = 1, @InputTemp = ABS(@InputNumber) WHILE(@Posisi <= 5) BEGIN SET @Mod = @InputTemp % 10 SET @InputTemp = @InputTemp / 10 SELECT @Hasil = CASE WHEN @Mod IN (0,1,2,3) THEN Replicate( SubString( @RomanLetter, @Posisi, 1 ), @Mod ) + @Hasil WHEN @Mod IN (4) THEN SubString( @RomanLetter, @Posisi, 2 ) + @Hasil WHEN @Mod IN (5,6,7,8) THEN SubString( @RomanLetter, @Posisi + 1, 1 ) + Replicate( SubString( @RomanLetter, @Posisi, 1 ), @Mod - 5 ) + @Hasil WHEN @Mod IN (9) THEN SubString( @RomanLetter, @Posisi, 1 ) + SubString( @RomanLetter, @Posisi + 2, 1 ) + @Hasil END SET @Posisi = @Posisi + 2 END SET @Hasil = Replicate('M', @InputTemp) + @Hasil IF @InputNumber < 0 SET @Hasil = '-' + @Hasil END RETURN @Hasil END GO |
credit to sql-bi-dev