请求协助解决SQL语句中的nvarchar转换失败错误
Hey there, let's break down this Conversion failed when converting nvarchar error you're hitting. This issue almost always stems from implicit data type mismatches—SQL Server tries to automatically convert between incompatible types during execution, and fails when it encounters values that can't be converted. Let's walk through the most likely culprits in your query:
1. Mismatched Data Types in the CASE Statement
Looking at your CASE clause:
CASE WHEN sh.CUSTOMER IN (46003204, 30321) THEN 'CHUB' ELSE '' END AS CUSTOMER
If the sh.CUSTOMER column is an nvarchar/varchar type (which makes sense for a customer identifier that might have non-numeric values), comparing it to numeric literals (46003204, 30321) forces SQL Server to convert all values in sh.CUSTOMER to numbers for the comparison. If even one row has a non-numeric CUSTOMER value, this conversion fails and throws your error.
Fix:
Update the IN clause to use string literals instead of numbers, matching the data type of sh.CUSTOMER:
CASE WHEN sh.CUSTOMER IN ('46003204', '30321') THEN 'CHUB' ELSE '' END AS CUSTOMER
2. Potential Type Mismatch in the Subquery
Your incomplete subquery:
(SELECT TOP 1 sd.customer_po FROM shipment_detail sd WHERE sd.internal_shipment_num = sh.internal_shipment_num...)
Could be another source of the error if:
sd.internal_shipment_numandsh.internal_shipment_numhave different data types (e.g., one is numeric, the other is nvarchar). SQL Server will again try implicit conversion here, which can fail if there are non-numeric values in the string column.- The
customer_povalue is being used in a context that expects a different type (e.g., concatenated with a numeric column later in the query).
Fix:
- Verify that
sd.internal_shipment_numandsh.internal_shipment_numhave matching data types. If not, use explicit conversion (e.g.,CAST(sh.internal_shipment_num AS NVARCHAR(20)) = sd.internal_shipment_num) to align them. - Ensure any operations involving
customer_pouse compatible types.
3. Quick Troubleshooting Steps to Isolate the Issue
If you're still unsure where the error is coming from:
- Test the CASE statement in isolation: Run
SELECT CASE WHEN sh.CUSTOMER IN (46003204, 30321) THEN 'CHUB' ELSE '' END FROM your_shipment_table_name sh—if this throws the same error, you've confirmed the root cause is here. - Check column data types: Use
sp_help 'your_shipment_table_name'to confirm the type ofsh.CUSTOMERand other join/comparison columns. - Trim down the query: Remove parts of the SELECT clause one by one until the error disappears—this will narrow down exactly which part is causing the conversion failure.
内容的提问来源于stack exchange,提问作者Dre

