3

I currently have a bunch of strings inside an Oracle database column that I need to change, right now I am running multiple update statements to accomplish this.

UPDATE TABLE1 SET COLUMN1 = REPLACE 
(COLUMN1, 'ABC', 'SR1')
UPDATE TABLE1 SET COLUMN1 = REPLACE  
(COLUMN1, '123', 'SR2')
UPDATE TABLE1 SET COLUMN1 = REPLACE  
(COLUMN1, 'XYZ', 'SR3')
UPDATE TABLE1 SET COLUMN1 = REPLACE    
(COLUMN1, '789', 'SR4')

Is there anyway for me to get this done in one go around for example

UPDATE TABLE1 
SET
COLUMN1 = REPLACE(COLUMN1, 'XYZ', 'SR3'), 
COLUMN1 = REPLACE(COLUMN1, '789', 'SR4')
0

3 Answers 3

8

You can nest the replace() calls:

UPDATE TABLE1
    SET COLUMN1 = REPLACE(REPLACE(REPLACE(REPLACE(COLUMN1, 'ABC', 'SR1'), '123', 'SR2'), 'XYZ', 'SR3'), '789', 'SR4');

Oracle also offers regexp_replace(). You might find this handy for some of your data transformations.

Sign up to request clarification or add additional context in comments.

3 Comments

You were faster :), just curious what is max nested func limit (255 or 32)?
how would I use regexp_replace to achieve the same thing? I'm worried I could run up against the maximum level nested functions
@lad2025 . . . I happen to know that in SQL Server it is about 32. I don't know what the limit is in Oracle.
2

You may create an UDF using an associative array.

CREATE OR REPLACE  FUNCTION my_replace (
    inp VARCHAR2
) RETURN VARCHAR2 IS
    v_out   VARCHAR2(1000) := inp;
    TYPE v_astype IS
        TABLE OF VARCHAR2(40) INDEX BY VARCHAR(40);
    v_pat      v_astype;
    v_idx      VARCHAR2(40);
BEGIN
   v_pat('ABC') := ('SR1');
   v_pat('123') := ('SR2');
   v_pat('XYZ') := ('SR3');
   v_pat('789') := ('SR4');
    v_idx := v_pat.first;
    WHILE v_idx IS NOT NULL LOOP
        v_out := replace(v_out,v_idx,v_pat(v_idx) );
        v_idx := v_pat.next(v_idx);
    END LOOP;
    RETURN v_out;
END; 
/

At least now, your update statement will look clean :

UPDATE TABLE1
    SET COLUMN1 = my_replace(column1) ;

Also, for Oracle 12c and above you may use inline function ( it works if you just want to use function in a select ).

https://oracle-base.com/articles/12c/with-clause-enhancements-12cr1

Comments

0

As this is Oracle you can write a PL/SQL function to do the conversion:

create or replace function multi_replace(vi_string varchar2) return varchar2 is
  vo_string varchar2(4000);
begin
  vo_string := vi_string;
  vo_string := replace(vo_string, 'XYZ', 'SR3');
  vo_string := replace(vo_string, '789', 'SR4');
  ...
  return vo_string;
end;

Then call it in a query:

update mytable set column1 = multi_replace(column1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.