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)
It's probably a bit messy rolling your own regexp to test for a number, but the code below might work. I think the other solution by Gabe involving a user defined function is more robust since you are using the built in Oracle functionality (and my regexp is probably not 100% correct) but it might be worth a go:
This will then give the following output:
It will convert 123 to 123, but 123a or 12a3 to 0.
This code excludes such strings as: -1-1, 1..1, 12-2 and so on. And I haven't used regular expressions here.
Fitting the original question and rather old skool
From
Oracle Database 12c Release 2
you could use TO_NUMBER withDEFAULT ... ON CONVERSION ERROR
:Or
CAST
:db<>fiddle demo
Best method seems to be the function solution but if you don't have necessary privileges in the environment you are struggling (like me), then you can try this one:
By the way: In my case the problem was due to "," and "." :) So take that into consider. Inspired from this one. Also this one seems more concise.
By the way 2: Dear Oracle, can you please create some built-in functions for such small but invaluable needs?