Safely convert VarChar that contains Numbers and Text to a Number – PL/SQL

The PL/SQL function TO_NUMBERS throws an exception ORA-01722: invalid number exception if any of the field values have a String or Alpha Numeric value.

Writing a PL/SQL Function or Stored Procedure to Capture the Exception and return a number, like the example shown below (CONVERT_TO_NUMBER) seems to Crash the AIX Server hosting the database under a heavy workload. So test this function before implementing it.

CREATE OR REPLACE FUNCTION CONVERT_TO_NUMBER(p_string IN VARCHAR2 )
  RETURN NUMBER
IS
  l_value NUMBER;
BEGIN
  l_value := to_number( p_string );
  RETURN l_value;
EXCEPTION
  WHEN others THEN
    RETURN 0;
END;

I have now moved to using the Query instead and this is backward compatible with Oracle 9.2 also

 TO_NUMBER(
 CASE
 WHEN MY_FIELD IS NULL THEN '0'
 WHEN LENGTH (TRIM (TRANSLATE (MY_FIELD, '0123456789', ' '))) IS NULL
 THEN MY_FIELD
 ELSE '0'
 END) AS MY_FIELD_NUM

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: