Sqlserver16进制与10进制的相互转换
程序员文章站
2024-03-18 14:18:46
...
字符串转16进制:
ALTER FUNCTION [dbo].[VarCharToHex] ( @Str VARCHAR(400) )
RETURNS VARCHAR(800)
AS
BEGIN
DECLARE @i INT ,
@Asi INT ,
@ModS INT ,
@res VARCHAR(800) ,
@Len INT ,
@Cres VARCHAR(4) ,
@tempstr VARBINARY(400);
SELECT @i = 1 ,
@res = '' ,
@Len = DATALENGTH(@Str) ,
@tempstr = CONVERT(VARBINARY, @Str);
WHILE @i <= @Len
BEGIN
SELECT @Asi = SUBSTRING(@tempstr, 1, 1) ,
@Cres = '';
WHILE @Asi <> 0
BEGIN
SELECT @ModS = @Asi % 16 ,
@Cres = CASE WHEN ( @ModS > 9 )
THEN CHAR(ASCII('A') + @ModS - 10)
+ @Cres
ELSE CAST(@ModS AS VARCHAR(4))
+ @Cres
END ,
@Asi = @Asi / 16;
END;
SELECT @res = @res + @Cres ,
@tempstr = SUBSTRING(@tempstr, 2, @Len - 1) ,
@i = @i + 1;
END;
RETURN @res;
END;
int转16进制字符串
ALTER FUNCTION [dbo].[IntToHex] ( @IntNum INT )
RETURNS VARCHAR(16)
AS
BEGIN
DECLARE @Mods INT ,
@res VARCHAR(16);
SET @res = '';
WHILE @IntNum <> 0
BEGIN
SET @Mods = @IntNum % 16;
IF @Mods > 9
SET @res = CHAR(ASCII('A') + @Mods - 10) + @res;
ELSE
SET @res = CAST(@Mods AS VARCHAR(4)) + @res;
SET @IntNum = @IntNum / 16;
END;
RETURN @res;
END;