Could somebody tell me how I can detect if a cast failed in MySQL using CAST()
function?
These two lines return the same value: 0.
SELECT CAST('Banana' AS UNSIGNED INTEGER) AS 'CAST1';
SELECT CAST('0' AS UNSIGNED INTEGER) AS 'CAST2';
You can use regular expressions to validate the data before the conversion:
select (case when val regexp '^[0-9]+$' then cast(val as unsigned integer) end)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With