进制转换基于一个原则: 求模倒到余。
SQL 中没有数组,所以只能用 表变量来表示。
如下:
alter function [F_ToRadixString](@num int , @radix int) returns varchar(500) as begin if ( @radix > 36 ) return null ; if ( @radix < 0 ) return null ; declare @flag bit; if ( @num < 0 ) set @flag = 0 ; else set @flag = 1 ; set @num = abs(@num) declare @ret varchar(50); set @ret = ''; declare @it table(i int identity(1,1), v char(1) ); insert into @it(v) values ('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9'),('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M'),('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z') while @num != 0 begin select @ret = @ret + v from @it where i -1 = (@num % @radix) set @num = @num / @radix end set @ret = REVERSE(@ret) if( @flag = 0) set @ret = '-' + @ret ; return @ret ; end ;
执行:
select dbo.[F_ToRadixString](35,36) => 'Z'
select dbo.[F_ToRadixString](-35,36) => '-Z'