I need to create an Oracle DB function that takes a string as parameter. The string contains letters and numbers. I need to extract all the numbers from this string. For example, if I have a string like RO1234, I need to be able to use a function, say
extract_number('RO1234'), and the result would be 1234.
To be even more precise, this is the kind of SQL query which this function would be used in.
SELECT DISTINCT column_name, extract_number(column_name) FROM table_name WHERE extract_number(column_name) = 1234;
QUESTION: How do I add a function like that to my Oracle database, in order to be able to use it like in the example above, using any of Oracle SQL Developer or SQLTools client applications?
REGEXP_REPLACE in order to remove all non-digit characters from a string:
select regexp_replace(column_name, '[^0-9]', '') from mytable;
select regexp_replace(column_name, '[^[:digit:]]', '') from mytable;
Of course you can write a function
extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.
create function extract_number(in_number varchar2) return varchar2 is begin return regexp_replace(in_number, '[^[:digit:]]', ''); end;
You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:
select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;
which will return "12345569".
also you can use this one:
select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers, regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters from dual
which will return "12345569" for numbers and "StackOverFlow" for characters.
If you are looking for 1st Number with decimal as string has correct decimal places, you may try
regexp_substr function like this:
This works for me, I only need first numbers in string:
the field had the following string:
"(43 Paginas) REGLAS DE PARTICIPACION".