Search code examples
sqloracle-databasecarriage-return

Oracle10g- Replace multiple carriage return


a query returns string like AAA[][]AAA[][][][]BBB[][]BBB . I need to replace the four consecutive carriage returns with a semicolon but not the consecutive two carriage returns. I have tried

replace(STRING,chr(13)||chr(13)||chr(13)||chr(13),';')

but it has no effect. Any help would be appreciated.


Solution

  • Use CHR(10) on linux/unix systems. On Windows, the carriage returns are composed of two characters CHR(10)||chr(13). On linux:

    SQL> WITH DATA AS (
      2     SELECT 'AAA
      3  
      4  AAA
      5  
      6  
      7  
      8  BBB
      9  
     10  BBB' txt FROM dual
     11  ) SELECT replace(txt, chr(10)||chr(10)||chr(10)||chr(10), ';') rep
     12      FROM DATA;
    
    REP
    ------------------------------
    AAA
    
    AAA;BBB
    
    BBB
    

    Since you you can use newlines directly in expressions, you can make it work on all platforms/character sets with newline characters (I would recommend this solution since it's portable):

    SQL> WITH DATA AS (
      2     SELECT 'AAA
      3  
      4  AAA
      5  
      6  
      7  
      8  BBB
      9  
     10  BBB' txt FROM dual
     11  ) SELECT replace(txt, '
     12  
     13  
     14  
     15  ', ';') rep FROM DATA;
    
    REP
    --------------------------
    AAA
    
    AAA;BBB
    
    BBB