Base 36 to Base 10 conversion using SQL only

后端 未结 2 1186
南旧
南旧 2020-12-01 11:08

A situation has arisen where I need to perform a base 36 to base 10 conversion, in the context of a SQL statement. There doesn\'t appear to be anything built into Oracle 9

2条回答
  •  -上瘾入骨i
    2020-12-01 11:35

    For T-SQL the following logic will perform the task that the Oracle code above does. This is generic general solution and will support Base-X to Base-10:

    select
        sum(power(base,pos-1) *
                case when substring(cnv,pos,1) between '0' and '9' then 
                    cast(substring(cnv,pos,1) as int) 
                else 10 + ascii(upper(substring(cnv,pos,1))) - ascii('A') end)
        from (values(reverse('01Z'), 36)) as t(cnv,base)
            left join (values(1),(2),(3),(4),(5),(6)) as x(pos)
                on pos <= len(cnv)
    

    To use with other bases just use:

    from (select cnv = reverse('FF'), base=16) as t
    

    or

    from (select cnv = reverse('101'), base=2) as t
    

    Note that to support strings longer than 6 you would need to add more values to the position vector.

提交回复
热议问题