views:

36

answers:

3

I have a hexadecimal string in a VARCHAR field and I need to convert it to VARBINARY.

How does one do this?

A: 

You could create the UDF used in this post. And then do:

SELECT CAST(dbo.Hex2Bin('7FE0') as VARBINARY(8000)) AS bin;
Abe Miessler
+1  A: 

Try this xml hack:

declare @hexstring varchar(max);
set @hexstring = '612E20';
select cast('' as xml).value('xs:hexBinary(sql:variable("@hexstring"))', 'varbinary(max)')
Denis Valeev
+1  A: 

If SQL Server 2008 you can do this straightforwardly via CONVERT

declare @hexstring varchar(max);
set @hexstring = 'abcedf012439';


/*SQL Server 2005 Specific*/
select cast('' as xml).value('xs:hexBinary( substring(sql:variable("@hexstring"), sql:column("t.pos")) )', 'varbinary(max)')

from (select case substring(@hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)


/*SQL Server 2008 Specific*/
set @hexstring = 'abcedf012439';
select CONVERT(varbinary(max), @hexstring, 2);

set @hexstring = '0xabcedf012439';
select CONVERT(varbinary(max), @hexstring, 1);

Source: http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx

Martin Smith