问题
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