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

后端 未结 3 1920
情书的邮戳
情书的邮戳 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条回答
  •  我在风中等你
    2020-12-19 08:28

    This is a solution:

    select
      pos
    from
      (select
        substr('SSSRNNSRSSR', level, 1) as character,
        level as pos
      from
        dual
      connect by
        level <= length(t.text))
    where
      character = 'R'
    

    dual is a built in table that just returns a single row. Very convenient!

    connect by lets you build recursive queries. This is often used to generate lists from tree-like data (parent/child relations). It allows you to more or less repeat the query in front of it. And you've got special fields, like level that allows you to check how deeply the recursion went.

    In this case, I use it to split the string to characters and return a row for each character. Using level, I can repeat the query and get a character until the end of the string is reached.

    Then it is just a matter of returning the pos for all rows containing the character 'R'

提交回复
热议问题