Simon's SQL

SQL,DBA,tuning,Trouble Shooting,Performance

Archive for January 31st, 2012

Converting from hex string to varbinary and vice versa

Posted by Simon Cho on 01/31/2012

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

SQL2005

-- Convert hexstring value in a variable to varbinary:
declare @hexstring varchar(max);
set @hexstring = 'abcedf012439';
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)
go

-- Convert binary value in a variable to hexstring:
declare @hexbin varbinary(max);
set @hexbin = 0xabcedf012439;
select '0x' + cast('' as xml).value('xs:hexBinary(sql:variable("@hexbin") )', 'varchar(max)');
go

SQL2008

declare @hexstring varchar(max);
set @hexstring = '0xabcedf012439';
select CONVERT(varbinary(max), @hexstring, 1);
set @hexstring = 'abcedf012439';
select CONVERT(varbinary(max), @hexstring, 2);
go

declare @hexbin varbinary(max);
set @hexbin = 0xabcedf012439;
select CONVERT(varchar(max), @hexbin, 1), CONVERT(varchar(max), @hexbin, 2);
go

Posted in Common | 1 Comment »