1

Got the following pl/sql function that extracts numbers from the string:

CREATE FUNCTION extract_number (
in_number VARCHAR2)
RETURN NUMBER IS
BEGIN
RETURN regexp_replace(in_number, '[^[:digit:]]', '');
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;

Need to put NULL where no numeric value was found (instead of just empty row). Example:

Got a table:

create table tab2 (val varchar2(100));
insert into tab2 (val) values ('2133jdhfjshd4');
insert into tab2 (val) values ('afafaf');
insert into tab2 (val) values ('skdjfj6787887hhh');
insert into tab2 (val) values ('324824898');
insert into tab2 (val) values ('4jh4jhh4');
commit;

This is an output from function:

          21334

        6787887
      324824898
            444

On the second row I need 'NULL' to be placed.

NO_DATA_FOUND not working. Please advise what should I do?

1
  • Warning: don't mess with data types! If the return value is NULL, why do you want to replace that with a four-letter string? As you saw already, using one of the proposed solutions, you will have to change the data type of the return - from number to varchar2. Presumably a function like this would be used to extract numbers from strings, to be used in further computations - as numbers. Change the function to return varchar2 instead, and a lot of other things will break. If you need to display "NULL" on reports, do it in the reporting layer, not in the function itself. Commented Aug 31, 2017 at 14:38

3 Answers 3

1

Wrap the regexp_replace in NVL():

NVL(regexp_replace(in_number, '[^[:digit:]]', ''), 'NULL');

If NULL is returned by regexp_replace(), return the string 'NULL'.

Documentation

Sign up to request clarification or add additional context in comments.

1 Comment

worked after replaced RETURN NUMBER in function to RETURN VARCHAR2
0

In sqlplus you can use this set null 'null'. And this is only for presentation.

I see few problem with your function.

  1. regexp_replace never throws no_data_found exception
  2. The result of regexp_replace is always varchar2 or null and oracle has to do the implicit conversion to the number.

Comments

0

There is no need of NO_DATA_FOUND . However you can raise it anyway..

CREATE FUNCTION extract_number (in_number VARCHAR2)
       RETURN NUMBER
    IS
       v_return   NUMBER (10);
    BEGIN
       v_return := REGEXP_REPLACE (in_number, '[^[:digit:]]', '');

       IF v_return IS NULL
       THEN
          RAISE NO_DATA_FOUND;
       END IF;

       RETURN v_return;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          RETURN NULL;
    END;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.