Convert a hexadecimal varbinary to its string representation?

≡放荡痞女 提交于 2020-06-16 07:42:26

问题


I have some base-64 encoded strings in SQL Server database, for example:

DECLARE @x VARBINARY(64);
SET @x = 0x4b78374c6a3733514f723444444d35793665362f6c513d3d

When it's CAST or CONVERTED to a VARCHAR, I get:

+˽Ð:¾Îréî¿•

I'm looking for SQL Server to return a varchar with the hexadecimal representation of the varbinary as a varchar, e.g.:

4b78374c6a3733514f723444444d35793665362f6c513d3d

Is there a build in CAST/CONVERT/function that does this, or does it have to be added as a User Defined Function? And what would the UDF be?

Bonus points if I can select whether I want capital A-F or lower case a-f in the conversion process.


回答1:


For SQL2005 I would use xsd:hexBinary data type:

DECLARE @x VARBINARY(64);
SET @x = 0x4b78374c6a3733514f723444444d35793665362f6c513d3d

SELECT '0x'+CONVERT(XML, '').value('xs:hexBinary(sql:variable("@x") )', 'VARCHAR(MAX)');
SELECT '0x'+LOWER(CONVERT(XML, '').value('xs:hexBinary(sql:variable("@x") )', 'VARCHAR(MAX)'));

For SQL2008+ I would use CONVERT (see section Binary styles):

SELECT CONVERT(VARCHAR(MAX), @x, 1)

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




回答2:


DECLARE @x VARBINARY(64);
SET @x = 0x4b78374c6a3733514f723444444d35793665362f6c513d3d;

SELECT CONVERT(VARCHAR(64), @x),
       SUBSTRING(CONVERT(VARCHAR(64), @x, 1), 3, 64);
       ----- style number is important ---^ 

Results:

Kx7Lj73QOr4DDM5y6e6/lQ==    4B78374C6A3733514F723444444D35793665362F6C513D3D

If you want lower case, just wrap the whole SUBSTRING operation in LOWER().

SQLFiddle demo



来源:https://stackoverflow.com/questions/19968728/convert-a-hexadecimal-varbinary-to-its-string-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!