将VARCHAR转换为BINARY(16):SQL Server二进制数据解码问题
Hey there, let’s work through this problem you’re facing—binary data stored in a varchar(400) column (SomeData in TABLE_TEST) that shows up fine when editing the table but garbles or doesn’t display correctly when running a SELECT query. I’ve helped folks with this exact scenario before, so let’s break down actionable solutions:
1. First, View the Raw Binary as Hexadecimal
The reason you can see the data in the table editor is likely because it’s rendering the binary content as hexadecimal, while a plain SELECT tries to interpret the varchar as text (which fails for non-printable binary bytes). To match what you see in the editor, convert the varchar to varbinary to get the raw hex representation:
SELECT CAST(SomeData AS VARBINARY(400)) AS RawBinaryHex FROM TABLE_TEST;
Or using CONVERT (same end result):
SELECT CONVERT(VARBINARY(400), SomeData) AS RawBinaryHex FROM TABLE_TEST;
This query will return the hexadecimal string of your binary data, just like what’s shown in the table edit interface.
2. Decode to Readable Text (If Applicable)
If the binary data was originally text (e.g., ASCII or Unicode) that got stored as varchar by mistake, you can convert it back after first casting to varbinary:
- For ASCII/ANSI text:
SELECT CONVERT(VARCHAR(400), CAST(SomeData AS VARBINARY(400))) AS DecodedText FROM TABLE_TEST; - For Unicode (UTF-16) text:
SELECT CONVERT(NVARCHAR(200), CAST(SomeData AS VARBINARY(400))) AS DecodedUnicodeText FROM TABLE_TEST;
Note: If the binary data is something non-text (like encrypted content, compressed data, or file blobs), this won’t work—you’ll need to use the appropriate decryption/decompression functions for that specific data type.
3. Handle Hexadecimal Strings Stored as VARCHAR
If the SomeData column actually stores hexadecimal strings (e.g., "0x1F8B0800..." or "1F8B0800...") instead of raw binary, you’ll need to convert those string values to actual binary data first:
- For strings with the
0xprefix:SELECT CONVERT(VARBINARY(400), SomeData, 1) AS ActualBinaryData FROM TABLE_TEST; - For strings without the
0xprefix:SELECT CONVERT(VARBINARY(400), SomeData, 2) AS ActualBinaryData FROM TABLE_TEST;
Once you have the actual binary data, you can then convert it to whatever format you need (text, etc.).
Why Your Previous Conversion Attempts Might Have Failed
Chances are you tried converting the varchar directly without first casting it to varbinary. Since varchar is a character type, any non-printable binary bytes get treated as invalid characters, which breaks string-based conversions. Always start by casting to varbinary to retrieve the original binary data before any further processing.
内容的提问来源于stack exchange,提问作者user7867434

