"Safe" TO_NUMBER()
SELECT TO_NUMBER('*') FROM DUAL
This obviously gives me an exception:
ORA-01722: invalid number
Is there a way to "skip" it and get 0
or NULL
instead?
The whole issue: I have NVARCHAR2
field, which contains numbers and not almost ;-) (like *
) and I need to select the biggest number from the column.
Yes, I know it is a terrible design, but this is what I need now... :-S
UPD:
For myself I've solved this issue with
COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+')), 0)
Solution 1:
From Oracle Database 12c Release 2
you could use TO_NUMBER with DEFAULT ... ON CONVERSION ERROR
:
SELECT TO_NUMBER('*' DEFAULT 0 ON CONVERSION ERROR) AS "Value"
FROM DUAL;
Or CAST
:
SELECT CAST('*' AS NUMBER DEFAULT 0 ON CONVERSION ERROR) AS "Value"
FROM DUAL;
db<>fiddle demo
Solution 2:
COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+(\.\d+)?')), 0)
will also get numbers with scale > 0 (digits to the right of the decimal point).
Solution 3:
I couldn't find anything better than this:
function safe_to_number(p varchar2) return number is
v number;
begin
v := to_number(p);
return v;
exception when others then return 0;
end;
Solution 4:
select COALESCE(TO_NUMBER(REGEXP_SUBSTR( field, '^(-|+)?\d+(\.|,)?(\d+)?$')), 0) from dual;
It will convert 123 to 123, but 123a or 12a3 to 0.