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

Byr*_*ock 3 sql-server sql-server-2005

我在VARCHAR字段中有一个十六进制字符串,我需要将其转换为VARBINARY.

怎么做到这一点?

Mar*_*ith 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);
Run Code Online (Sandbox Code Playgroud)

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