SQL十进制和十六进制相互转换
CREATE FUNCTION ufn_ConvertInt2Hex ( @Num BIGINT ) RETURNS VARCHAR(500) AS BEGIN /************************************** -- 功能:十进制转十六进制 -- 作者:GarsonZhang -- 时间:2016年5月28日13:26:55 -- 测试: PRINT dbo.ufn_ConvertInt2Hex(50) **************************************/ DECLARE @Result VARCHAR(500) SET @Result = '' WHILE ( @Num > 0 ) BEGIN SET @Result = SUBSTRING('0123456789ABCDEF', @Num % 16 + 1, 1) + @Result SET @Num = @Num / 16 END RETURN @Result END GO CREATE FUNCTION ufn_ConvertHex2Int ( @HexString VARCHAR(16) ) RETURNS BIGINT AS /************************************** -- 功能:十六进制转十进制 -- 作者:GarsonZhang -- 时间:2016年5月28日13:30:24 -- 测试: PRINT dbo.ufn_ConvertInt2Hex(50) **************************************/ BEGIN DECLARE @Result BIGINT DECLARE @i INT , @len INT DECLARE @power BIGINT SET @power = 16 SELECT @i = 0 , @Result = 0 , @HexString = RTRIM(LTRIM(UPPER(@HexString))) SET @len = LEN(@HexString) IF ( @len = 16 ) BEGIN IF ( ASCII(SUBSTRING(@HexString, 1, 1)) > 55 ) BEGIN -- RaisError('超出数据运算范围', 1, 16) RETURN @Result END END ------------------------------------------------------- WHILE ( @i < @len ) BEGIN IF ( ( SUBSTRING(@HexString, @len - @i, 1) NOT BETWEEN '0' AND '9' ) AND ( SUBSTRING(@HexString, @len - @i, 1) NOT BETWEEN 'A' AND 'F' ) ) BEGIN SET @Result = 0 BREAK; END ---------------------------------------- SET @Result = @Result + ( CHARINDEX(SUBSTRING(@HexString, @len - @i, 1), '0123456789ABCDEF') - 1 ) * CAST(POWER(@power, @i) AS BIGINT) SET @i = @i + 1 END ---------------------------------------------- RETURN @Result END
慎于行,敏于思!GGGGGG