Reverse String Word by Word using SQL

后端 未结 5 1471
半阙折子戏
半阙折子戏 2020-12-15 13:19

I would need to reverse the word positions in a sentence or String.

For example : \"Hello World! I Love StackOverflow\", to be displayed as \"StackOverflow          


        
5条回答
  •  萌比男神i
    2020-12-15 13:48

    XML-based version to avoid defining your own function; requires 11g for listagg():

    select listagg(word, ' ') within group (order by rn desc) as reversed
    from (
      select word, rownum as rn
      from xmltable('for $i in ora:tokenize($STR, " ") return $i'
        passing 'Hello World! I Love StackOverflow' as str
        columns word varchar2(4000) path '.'
      )
    );
    
    REVERSED                               
    ----------------------------------------
    StackOverflow Love I World! Hello        
    

    The XMLTable() does the tokenising, and assigns a row number:

    select rownum as rn, word
    from xmltable('for $i in ora:tokenize($STR, " ") return $i'
      passing 'Hello World! I Love StackOverflow' as str
      columns word varchar2(4000) path '.'
    );
    
            RN WORD               
    ---------- --------------------
             1 Hello                
             2 World!               
             3 I                    
             4 Love                 
             5 StackOverflow        
    

    The listagg() then pieces it back together in reverse order.

提交回复
热议问题