Search code examples
oracle-databasesubstrclob

Oracle loop through CLOB to get string


I want to convert all data in CLOB to string. DBMC_LOB.SUBSTR provides a way to fetch 4000 characters at once. I am from MS SQL background and not aware of Oracle queries. Can someone help me with the syntax.

I want to make a function and do something like

// Get the length of CLOB
// totalIterationsRequired = length/4000;
// LOOP around the CLOB and fetch 4000 char at once 
For i in 1..totalIterationsRequired
LOOP
// Insert the substring into a varchar2
//  DBMC_LOB.SUBSTR(xml_value,4000*i,(4000*(i-1)+1)
END LOOP
// The function will return the varchar2

Solution

  • create table save_table(rec varchar2(4000));
    
    create or replace PROCEDURE save_clob (p_clob IN CLOB)
    AS
        l_length             INTEGER;
        l_start              INTEGER := 1;
        l_recsize   CONSTANT INTEGER := 4000;
    BEGIN
        l_length   := DBMS_LOB.getlength (p_clob);
    
        WHILE l_start <= l_length
        LOOP
            INSERT INTO save_table (rec)
                 VALUES (DBMS_LOB.SUBSTR (p_clob, l_recsize, l_start));
    
            l_start   := l_start + l_recsize;
        END LOOP;
    END save_clob;