SQL Server中使用Style 2转换Varchar到VarBinary部分值报错求助
Hey there! Let's break down why your conversion is failing and how to fix it.
问题根源
When using CONVERT(VARBINARY, ..., 2) (Style 2), SQL Server expects the input varchar string to meet two strict requirements:
- It must contain only valid hexadecimal characters (0-9, A-F, a-f)
- The length of the string must be even — because each byte in varbinary is represented by two hex characters.
Looking at your examples:
'AFE27AF97DC6'is 12 characters (even) → works perfectly, since it maps to 6 bytes of binary data.'AFEE27AF97DC6'is 13 characters (odd) → there's no way to split an odd number of hex chars into whole bytes, so SQL Server throws theError converting data type varchar to varbinaryerror.
解决方案
Here are a few approaches to fix this:
Fix the input string length
Depending on your business logic, you can either:- Trim the extra character if it's a typo (e.g., remove the extra
Eto get back to an even-length string) - Pad the string with a leading or trailing
0to make its length even. For example:-- Pad with leading 0 SELECT CONVERT(VARBINARY(MAX), '0AFEE27AF97DC6', 2) -- Or pad with trailing 0 SELECT CONVERT(VARBINARY(MAX), 'AFEE27AF97DC60', 2)
Note: Make sure padding aligns with your data's actual meaning — don't just add a 0 randomly!
- Trim the extra character if it's a typo (e.g., remove the extra
Validate input before conversion
UseTRY_CONVERTinstead ofCONVERTto avoid hard errors; it will returnNULLfor invalid inputs instead of throwing an exception:SELECT TRY_CONVERT(VARBINARY(MAX), 'AFEE27AF97DC6', 2)You can also add a check for even length upfront:
SELECT CASE WHEN LEN(your_column) % 2 = 0 THEN CONVERT(VARBINARY(MAX), your_column, 2) ELSE NULL -- Or handle the odd-length case as needed END FROM your_tableEnsure no invalid characters
Double-check that your input strings don't contain non-hex characters (like G-Z, symbols, etc.) — those will also trigger the same conversion error.
内容的提问来源于stack exchange,提问作者rav




