Author: Various (incl. Pinal Dave and the original 2000/5 from PDreyer
Date: 9 Jul 2008
When I went to publish this tip, I looked at the code i had stored and something didn't seem quite right. It had become corrupted over the years. I searched out a much better function-based version which is published below and is valid for all versions of SQL Server.
However, from SQL 2008 onwards, the CAST/CONVERT functions are able to perform this conversion directly, with the HEX represented as either a VARBINARY token, or a HEX character string with or without the '0x' prefix.
-- FOR SQL 2000/2005 (and 2008/12 if required)
CREATE FUNCTION dbo.fn_Hex2BigInt(@s VARCHAR(16)) --Convert hex to bigint
RETURNS BIGINT -- e.g. select dbo.fn_Hex2BigInt('7ff2a5')
WHEN @len>0 THEN 0
WHEN @c BETWEEN 'A' AND 'F' THEN 55
WHEN @c BETWEEN '0' AND '9' THEN 48
)) * POWER(16.,@len-@i),
END -- while
END -- function
-- for SQL 2008 , 2008R2, 2012
DECLARE @s VARCHAR(16)
--for a hex string that has no '0x' prefix
SELECT @s = '7ff2a5'
SELECT CAST(CONVERT(VARBINARY, @s, 2) AS BIGINT)
--for a hex string that has an '0x' prefix
SELECT @s = '0x7ff2a5'
SELECT CAST(CONVERT(VARBINARY, @s, 1) AS BIGINT)