开发者

How do i convert a hexadecimal VARCHAR to a VARBINARY in SQL Server

开发者 https://www.devze.com 2023-01-17 08:34 出处:网络
I have a hexadecimal string in a VARCHAR field and I need to convert it to VARBINARY. How does one 开发者_运维知识库do this?If SQL Server 2008 you can do this straightforwardly via CONVERT

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

How does one 开发者_运维知识库do this?


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


Try this xml hack:

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


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

SELECT CAST(dbo.Hex2Bin('7FE0') as VARBINARY(8000)) AS bin;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号