Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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) 
like image 548
zerkms Avatar asked Dec 20 '10 04:12

zerkms


People also ask

Can we convert number to char in Oracle?

TO_CHAR (number) converts n to a value of VARCHAR2 datatype, using the optional number format fmt . The value n can be of type NUMBER , BINARY_FLOAT , or BINARY_DOUBLE . If you omit fmt , then n is converted to a VARCHAR2 value exactly long enough to hold its significant digits.

How do I cast a string in Oracle?

Let's look at some Oracle CAST function examples and explore how to use the CAST function in Oracle/PLSQL. For example: select CAST( '22-Aug-2003' AS varchar2(30) ) from dual; This would convert the date (ie: 22-Aug-2003) into a varchar2(30) value.

What is type casting in Oracle?

CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value. CAST lets you convert built-in datatypes or collection-typed values of one type into another built-in datatype or collection type.


1 Answers

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

like image 150
Lukasz Szozda Avatar answered Sep 24 '22 12:09

Lukasz Szozda