Hi Team
I want to write this query and getting this sql exception for using Error converting data type nvarchar to numeric. Where can improve this query?
WITH PremixCalculation AS (
SELECT
Adr_Batch_Log.MatDesc,
Adr_Batch_Log.MatCode,
Adr_Batch_Log.Shift,
Adr_Batch_Log.Batched,
CASE
WHEN Adr_Batch_Log.MatCode LIKE 'MR%' THEN 1 * COALESCE(CAST(NULLIF(Adr_Batch_Log.MatUnit, '') AS DECIMAL(18, 3)), 0) * Adr_Batch_Log.Shift * Adr_Batch_Log.Batched
WHEN Adr_Batch_Log.MatCode LIKE 'RB%' THEN 25 * COALESCE(CAST(NULLIF(Adr_Batch_Log.MatUnit, '') AS DECIMAL(18, 3)), 0) * Adr_Batch_Log.Shift * Adr_Batch_Log.Batched
ELSE 0
END AS Premix
FROM
Adroit_Batch_Suite.dbo.Adr_Batch_Log Adr_Batch_Log
WHERE
Adr_Batch_Log.dt >= '2024-06-01' AND Adr_Batch_Log.dt < '2024-06-02'
AND (Adr_Batch_Log.MatCode LIKE 'MR%' OR Adr_Batch_Log.MatCode LIKE 'RB%')
)
SELECT
MatDesc,
SUM(Premix) AS TotalPremix
FROM
PremixCalculation
GROUP BY
MatDesc;
Uday DodiyaPosted Jun 13, 2024, 1:14 PM
The error "Error converting data type nvarchar to numeric" typically arises when there is an attempt to convert non-numeric strings to a numeric type. In this case, the issue is likely due to the
CAST(NULLIF(Adr_Batch_Log.MatUnit, '') AS DECIMAL(18, 3))part of the query. IfAdr_Batch_Log.MatUnitcontains non-numeric values or empty strings, this conversion will fail.To handle this, you can use a
CASEstatement to ensure that only numeric values are converted. Here’s how you can adjust your query:TRY_CASTto safely attempt the conversion to a numeric type. If the conversion fails,TRY_CASTwill returnNULLinstead of throwing an error.MatUnitis numeric before attempting the conversion.Here is the revised query:
In this query:
TRY_CASTattempts to convertAdr_Batch_Log.MatUnittoDECIMAL(18, 3). If the conversion fails, it returnsNULL.COALESCEthen handles theseNULLvalues by converting them to0.This approach ensures that any non-numeric values inMatUnitdo not cause the query to fail.