如何在SQL Server中将十六进制VARCHAR转换为VARBINARY

3

我有一个存储在VARCHAR字段中的十六进制字符串,我需要将它转换为VARBINARY。

如何进行转换呢?

3个回答

11
如果使用 SQL Server 2008,您可以通过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);

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

本文介绍了如何在SQL Server中将十六进制字符串转换为VARBINARY类型,并将VARBINARY类型转换为十六进制字符串。可以使用CAST或CONVERT函数来实现这一点,也可以创建一个用户定义的函数来简化过程。

2
尝试使用这个XML技巧:
declare @hexstring varchar(max);
set @hexstring = '612E20';
select cast('' as xml).value('xs:hexBinary(sql:variable("@hexstring"))', 'varbinary(max)')

1
你可以创建 此篇文章中 使用的 UDF。然后执行以下操作:
SELECT CAST(dbo.Hex2Bin('7FE0') as VARBINARY(8000)) AS bin;

这就是我最终使用的内容。 - Byron Whitlock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接