I have a hexadecimal string in a VARCHAR field and I need to convert it to VARBINARY.
How does one do this?
I have a hexadecimal string in a VARCHAR field and I need to convert it to VARBINARY.
How does one do this?
You could create the UDF used in this post. And then do:
SELECT CAST(dbo.Hex2Bin('7FE0') as VARBINARY(8000)) AS bin;
Try this xml hack:
declare @hexstring varchar(max);
set @hexstring = '612E20';
select cast('' as xml).value('xs:hexBinary(sql:variable("@hexstring"))', 'varbinary(max)')
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);