Ankit
Ankit

Reputation: 6654

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

Upvotes: 0

Views: 6884

Answers (2)

Ankit
Ankit

Reputation: 6654

Below is the function definition

create or replace function getclobastable (id IN VARCHAR2) 
  return clob_table
is
    l_length             INTEGER;
    l_start              INTEGER := 1;
    l_recsize   CONSTANT INTEGER := 4000;
    i_clob                 CLOB;
    n BINARY_INTEGER := 0;
    save_table clob_table := clob_table();
BEGIN

    save_table := clob_table();
    -- Get the CLOB data into i_clob
    l_length := DBMS_LOB.getlength (i_clob);

    WHILE l_start <= l_length
    LOOP
        n := n + 1;

        save_table.EXTEND();
        save_table(n) := DBMS_LOB.SUBSTR (i_clob, l_recsize, l_start);

        l_start   := l_start + l_recsize;
    END LOOP;
    RETURN save_table;
END;

Upvotes: 0

Brian Leach
Brian Leach

Reputation: 2101

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;

Upvotes: 2

Related Questions