十进制/十八进制的互转换(此方法应用于所有进制与10进制的转换)
------十进制转换为十八进制
create function F_int18(@num int)
returns nvarchar(50)
as
begin
if @num=0
return '0'
declare @s nvarchar(50)
set @s=''
while @num>0
select @s=substring('0123456789ABCDEFHG',@num%18+1,1)+@s,@num=@num/18
return @s
end
go
----------十八进制转换为十进制
create function F_int10(@s nvarchar(50))
returns int
as
begin
declare @i int,@s2 nvarchar(2),@num int
select @i=len(@s),@num=0
while @i>0
select @s2=substring(reverse(@s),@i,1),
@num=power(18,@i-1)*(charindex(@s2,'0123456789ABCDEFHG')-1)+@num,
@i=@i-1
return @num
end
go
select dbo.F_int18(9999)
select dbo.F_int10('1CF9')
/*
--------------------------------------------------
1CF9
(所影响的行数为 1 行)
-----------
9999
(所影响的行数为 1 行)
*/
create function F_int18(@num int)
returns nvarchar(50)
as
begin
if @num=0
return '0'
declare @s nvarchar(50)
set @s=''
while @num>0
select @s=substring('0123456789ABCDEFHG',@num%18+1,1)+@s,@num=@num/18
return @s
end
go
----------十八进制转换为十进制
create function F_int10(@s nvarchar(50))
returns int
as
begin
declare @i int,@s2 nvarchar(2),@num int
select @i=len(@s),@num=0
while @i>0
select @s2=substring(reverse(@s),@i,1),
@num=power(18,@i-1)*(charindex(@s2,'0123456789ABCDEFHG')-1)+@num,
@i=@i-1
return @num
end
go
select dbo.F_int18(9999)
select dbo.F_int10('1CF9')
/*
--------------------------------------------------
1CF9
(所影响的行数为 1 行)
-----------
9999
(所影响的行数为 1 行)
*/