Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating CLOB field in Oracle

Tags:

oracle

clob

I have a table in Oracle database with field with data type CLOB. The name of field is XMLString. I am storing XML string which is 10,000 characters long for each record. I have more than 100, 000 of records in this table.

I need to update segment of the XML string on each record at specific place. For example I need to update each record at 14th position with some string like "My New text". This replacement text is 11 characters long. So this simply means it will replace 11 characers starting from 14th character.

I tried to use DBMS_LOB.FRAGMENT_REPLACE, but it is not exactly what I wanted.

Is there any simple command like

Replace(XMLString, 14, ‘My New text’) 

so that I can do something like below?

UPDATE MYTABLE 
SET MyClobField = Replace(MyClobField, 14, 'My New text')
WHERE MyTableID>5000

Any help would be appreciated.

like image 410
Shai Avatar asked Nov 26 '12 16:11

Shai


People also ask

How do I update CLOB fields?

Update clob column updating lob by using sql update You can updatetheLOBusing a bind variable in embedded SQL, the value of which may beNULL, empty, orpopulated. When you set oneLOBequal to another, a new copy of theLOBvalue is created.

How do I replace a string in a CLOB in Oracle?

DECLARE result CLOB; BEGIN result:='I need to replace this <my_tag>Everything can be here </my_tag>'; -- Some operation to replace '<my_tag>Everything can be here </my_tag>' with '<It works/>' DBMS_OUTPUT.


1 Answers

SQL using

UPDATE MYTABLE 
SET MyClobField = substr(MyClobField, 1, 10) || to_clob('MyNewtext')||substr(MyClobField, 10+length('MyNewtext')+1)
where..

just change the 2 occurrences of "10" to the offset.

or in PL/SQL like this using the DBMS_LOB.WRITE API (this is faster than the above)

SQL> create table foo(c clob);

Table created.

SQL> insert into foo values ( 'this is a test string ' || rpad('x', 20, 'x'));

1 row created.

SQL> commit;

Commit complete.

SQL> select * from foo;

C
--------------------------------------------------------------------------------
this is a test string xxxxxxxxxxxxxxxxxxxx

SQL> declare
  2    v_lob clob;
  3  begin
  4
  5    for r_lob in (select c
  6                    from foo
  7                    for update)
  8    loop
  9      dbms_lob.write(r_lob.c, 6, 16, 'phrase'); -- ie write at offset 16, 6 bytes
 10    end loop;
 11  end;
 12  /

PL/SQL procedure successfully completed.

SQL> select * from foo;

C
--------------------------------------------------------------------------------
this is a test phrase xxxxxxxxxxxxxxxxxxxx
like image 155
DazzaL Avatar answered Nov 04 '22 22:11

DazzaL