When I was modifying a code bug recently, I found that SQL error was reported. Finally, I found the reason was to directly sum the varchar data. The final modification plan determined that data type conversion was required.
The CAST method used here converts data types.
The final data is as follows:
select SUM(cast(changeData as numeric(12,0))) from testTable where departmentID='REACH & DEVELOPMENT';
The above changeData field is the varchar field
But in fact, it was a join table query, and part of the varchar in the database in the first table was '', so the final actual method was to convert the data in the temporary subtable first, and then perform the sum externally, similar to the following method:
SELECT
department.departmentID departmentID,
department.departmentName departmentName,
sum(offerData.changeData) changeData
FROM department ,
( SELECT
CASE WHEN changeTable.changeData = '' THEN 0
ELSE CAST(changeTable.changeData AS numeric(12,0))
END AS changeData,
switchTable.ID AS departmentID
FROM
changeTable,switchTable
WHERE
changeTable.ID = switchTable.changeID) AS offerData
WHERE offerData.departmentID = department.departmentID;
By using the SQL statement case when to first process the case where the data is '', and then perform the sum, the error can be avoided.