Multiple REPLACE function in Oracle

后端 未结 6 1798
陌清茗
陌清茗 2020-12-05 07:25

I am using the REPLACE function in oracle to replace values in my string like;

 SELECT REPLACE(\'THE NEW VALUE IS #VAL1#\',\'#VAL1#\',\'55\') fr         


        
6条回答
  •  醉酒成梦
    2020-12-05 07:56

    The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

    If you are going to make heavy use of this, you could consider writing your own function:

    CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
    
    CREATE FUNCTION multiple_replace(
      in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
    )
      RETURN VARCHAR2
    AS
      v_result VARCHAR2(32767);
    BEGIN
      IF( in_old.COUNT <> in_new.COUNT ) THEN
        RETURN in_text;
      END IF;
      v_result := in_text;
      FOR i IN 1 .. in_old.COUNT LOOP
        v_result := REPLACE( v_result, in_old(i), in_new(i) );
      END LOOP;
      RETURN v_result;
    END;
    

    and then use it like this:

    SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                             NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                             NEW t_text( 'text', 'tokens', 'replace' )
                           )
    FROM dual
    

    This is text with some tokens to replace

    If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

提交回复
热议问题