Oracle query to find all occurrences of a charcter in a string

后端 未结 3 1921
情书的邮戳
情书的邮戳 2020-12-19 07:51

I have to write an Oracle query in toad to find all the occurrences of a character in a string. For example if I\'m searching for R in the string SSSRNNSR

3条回答
  •  旧时难觅i
    2020-12-19 08:49

    To take up a_horse_with_no_name's challenge here is another answer with a pipelined table function.

    A pipelined function returns an array, which you can query normally. I would expect that over strings with large numbers of matches this will perform better than the recursive query but as with everything test yourself first.

    create type num_array as table of number
    /
    
    
    create function string_indexes (
        PSource_String in varchar2
      , PSearch_String in varchar2
        ) return num_array pipelined is
    
    begin
    
       for i in 1 .. length(PSource_String) loop
    
          if substr(PSource_String, i, 1) = PSearch_String then
             pipe row(i);
          end if;
    
       end loop;
    
       return;
    
    end;
    /
    

    Then in order to access it:

    select *
      from table(string_indexes('SSSRNNSRSSR','R'))
    

    SQL Fiddle

提交回复
热议问题