Getting a hexadecimal value from integer in SQL Server

Posted by Max | Posted in programming | Posted on 11-09-2009

0

There seems to be no any built-in function in SQL Server to format integer value as hexadecimal string. Here is the custom function for SQL server which does that:

For example to the following code displays the value 4095:


SELECT dbo.ToHex(4095) --> FFF

CREATE FUNCTION ToHex(@value int)
RETURNS varchar(50)
AS
BEGIN
    DECLARE @seq char(16)
    DECLARE @result varchar(50)
    DECLARE @digit char(1)
    SET @seq = '0123456789ABCDEF'

    SET @result = SUBSTRING(@seq, (@value%16)+1, 1)

    WHILE @value > 0
    BEGIN
    	SET @digit = SUBSTRING(@seq, ((@value/16)%16)+1, 1)

    	SET @value = @value/16
    	IF @value  0 SET @result = @digit + @result
    END 

    RETURN @result
END
GO

Write a comment