'How can I select convert a VARBINARY column (containing a text file) to an actual text string?

I have a SQL Server table with a VARBINARY column, which contains values like these:

0x500073007900630068006F006C006F0067006900630061006C00200053007400720061007400...

These values represent HTML files.

I'm trying to figure out how to SELECT these values as HTML strings.

I tried selecting CONVERT(VARCHAR(max), Content, 2) AS ContentConverted – but that just gave me the same value with the 0x prefix removed:

500073007900630068006F006C006F0067006900630061006C00200053007400720061007400...

I also tried CAST(Content AS VARCHAR(max)) AS ContentConverted – but that (bizarrely) just gives me a single letter:

P

Lastly, I tried this hack:

CAST(CONCAT('<?xml version="1.0" encoding="UTF-8" ?><![CDATA[',Content,']]>') AS XML).value('.','nvarchar(max)')

...and that just produces an "illegal xml character" error.

Any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source