Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Oracle INSTR function to search for multiple strings

In Oracle/PLSQL, the instr function returns the location of a sub-string in a string.

If the sub-string is not found, then instr will return 0.

I want to search multiple sub-strings in a string and return the first non-zero value. This can be achieved using regexp_instr, but I'd like a non-regexp_ solution.

Example:

regexp_instr('500 Oracle Parkway, Redwood Shores, CA','(Apple|Park|Shores)')

should return 12 (the location of 'Park').

like image 887
Rudiger Avatar asked Jan 06 '10 16:01

Rudiger


2 Answers

INSTR doesn't support regex ORs - you'd have to define INSTR function calls for each substring you want to check for. The equivalent of regexp_instr('500 Oracle Parkway, Redwood Shores, CA','(Apple|Park|Shores)') would be:

WHERE (INSTR('500 Oracle Parkway, Redwood Shores, CA', 'Apple') > 0
      OR
      INSTR('500 Oracle Parkway, Redwood Shores, CA', 'Park') > 0
      OR
      INSTR('500 Oracle Parkway, Redwood Shores, CA', 'Shores') > 0)

Depending on your needs, full text search functionality might be more towards what you want?

like image 193
OMG Ponies Avatar answered Sep 28 '22 00:09

OMG Ponies


Obviously without regexp there won't be such an elegant solution, unless you write your own PL/SQL function that does the same job. Otherwise you would have to do something like this:

with data as (select '500 Oracle Parkway, Redwood Shores, CA' string from dual)
select nvl(min(pos),0) from
( select instr(data.string, 'Apple') pos
  union all
  select instr(data.string, 'Park') pos
  union all
  select instr(data.string, 'Shores') pos
)
where pos > 0;
like image 35
Tony Andrews Avatar answered Sep 27 '22 23:09

Tony Andrews