Tuesday, August 16, 2016

How to Extract long data to Clob?

until to oracle 11G, oracle dictionary still includes some long data type, I try to use to_lob/Dbms_Lob.substr, it always raise oracle error "ORA-00932: inconsistent datatypes: expected - got LONG", so search some documents and give below function to extract the long data to clob.

select to_char(LONG2CLOB('COLUMN_EXPRESSION','ALL_IND_EXPRESSIONS','table_name=upper(''***'')')) as
from dual;


CREATE OR REPLACE FUNCTION LONG2CLOB (
   colName   IN VARCHAR2,
   tabName   IN VARCHAR2,
   whereCond IN VARCHAR2 := NULL)
RETURN CLOB
IS
   v_cur            PLS_INTEGER := DBMS_SQL.OPEN_CURSOR;
   v_rows           PLS_INTEGER;
   v_buflen         PLS_INTEGER := 32760;
   v_curpos         NUMBER := 0;
   v_long_len       NUMBER;
   v_long_val       CLOB;
   v_return_val     CLOB;
  BEGIN
   /* dynamic to execute the SQL */
   DBMS_SQL.PARSE (
      v_cur,
      'SELECT ' || colName ||
      '  FROM ' || tabName ||
      ' WHERE ' || NVL (whereCond, '1 = 1'),
      DBMS_SQL.NATIVE);

   /* Define the long column and then execute and fetch... */
   DBMS_SQL.DEFINE_COLUMN_LONG (v_cur, 1);
   v_rows := DBMS_SQL.EXECUTE (v_cur);
   v_rows := DBMS_SQL.FETCH_ROWS (v_cur);

   /* If a row was fetched, loop through the long value until
   || all pieces are retrieved.
   */
   IF v_rows> 0
   THEN
      LOOP
         DBMS_SQL.column_value_long (v_cur,
                                     1,
                                     v_buflen,
                                     v_curpos,
                                     v_long_val,
                                     v_long_len);
       
       
         EXIT WHEN v_long_len = 0;
         v_return_val := v_return_val || v_long_val;
         v_curpos := v_curpos + v_long_len;
      END LOOP;
   END IF;
   DBMS_SQL.CLOSE_CURSOR (v_cur);
   RETURN v_return_val;
EXCEPTION
   WHEN OTHERS
   THEN
      IF DBMS_SQL.is_open (v_cur)
      THEN
         DBMS_SQL.close_cursor (v_cur);
      END IF;
      RAISE;
END LONG2CLOB;
/

No comments:

Post a Comment