CLOB to VARCHAR2

I NEED TO CONVERT A VARCHAR2 TO CLOB AND VICE VERSA.
THANK YOU.

If you expect to convert the VARCHAR2 data into CLOB in table, you may directly save into that table CLOB column; If you want to save CLOB data into VARCHAR2 cloumn, then I don't feel it is feasible.
There is DBMS_LOB package, I doubt it to allow the convert CLOB back to VARCHAR2 even though it have procedures of SUBSTR(), TRIM() ...

Similar Messages

  • Chnage colum from CLOB to Varchar2 and find the length of CLOB

    Hi,
    I have got tables contain CLOB fields. I want to converter them to varchar2? Is the a way to do it? how can I find the max of length the data in CLOB fields.
    Thanks in advance!!
    Michael

    Hi All,
    Thanks you for your useful information. What I need is to change the colum data type (definaition itself)from CLOB to Varchar2, not just to display the values in CLOB field into varchar2. I have tried to change the date type from COLB to varchar2 in TOAD and got ORA_22859: invaliad modification of columns.
    Any suggestions?
    Many Thanks
    Michael

  • Clob to varchar2 + metadata + dbms_output = nothing:(

    Hi all! I am in trouble:) i don't know why am getting nothing, i expect either a result or an error, but not nothing.
    I want to print dll of an object in dbms_output
    create or replace procedure tomkyte.buildConstraint(
         cons_name varchar2,
         cons_owner varchar2)
         authid current_user
         AS
    statement clob;
    begin
         dbms_output.put_line('constraint: ' || cons_name);
         dbms_output.put_line('oowner : ' || cons_owner);
         select DBMS_METADATA.GET_DDL('CONSTRAINT',cons_name,cons_owner)
         into statement from dual;
         dbms_output.put_line(tomkyte.lob_to_char(statement)); -- if i coment this line i'll get a result!
    end;
    create or replace function tomkyte.lob_to_char(
         clob_col clob)
                        return varchar2
                        authid current_user
                        is
    buffer varchar2(4000);
    amt binary_integer := 4000;
    pos integer := 1;
    l clob;
    bfils bfile;
    l_var varchar2(4000):='';
    begin
         loop
              if dbms_lob.getlength(clob_col)<=4000
                   then dbms_lob.read (clob_col, amt, pos, buffer);
                   l_var := l_var||buffer;
                   pos:=pos+amt;
              else
                   l_var:= 'Cannot convert to varchar2..';
                   exit;
              end if;
         end loop;
    return l_var;
    exception
              when no_data_found then return l_var;
    end;

    Junior sysdba wrote:
    Hi all! I am in trouble:) i don't know why am getting nothing, i expect either a result or an error, but not nothing.
    I want to print dll of an object in dbms_output
         dbms_output.put_line(tomkyte.lob_to_char(statement)); -- if i coment this line i'll get a result!
    Hi,
    sql*plus 9.0.1.0.0
    dbms_output.put_line has a maximum of 256 characters, even in toad.
    You can try and use a formula to break apart the result in blocks of 256 or less chars.
    With error:
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2  statement clob;
      3  begin
      4  select DBMS_METADATA.GET_DDL('CONSTRAINT','REG_ID_PK','HR')
      5  into statement from dual;
      6  dbms_output.put_line(lob_to_char(statement)); -- if i coment this line i'll get a result!
      7  dbms_output.put_line('TEST');
      8* end;
    SQL> /
    ERROR:
    ORA-06502: PL/SQL: numeric or value error: host bind array too small
    ORA-06512: at line 1Without error (example with hard coded length)
    SQL> declare
      2  statement clob;
      3 
      4  begin
      5 
      6  select DBMS_METADATA.GET_DDL('CONSTRAINT','REG_ID_PK','HR')
      7  into statement from dual;
      8 
      9  --Dbms_output.put_line(lob_to_char(statement)); -- if i coment this line i'll get a result!
    10 
    11  Dbms_output.put_line(SUBSTR(lob_to_char(statement),1,255));
    12  Dbms_output.put_line(SUBSTR(lob_to_char(statement),256,321));
    13 
    14  end;
    15  /
      ALTER TABLE "HR"."REGIONS" ADD CONSTRAINT "REG_ID_PK" PRIMARY KEY ("REGION_ID")
      USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
      STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
      PCTINCREASE 0 FREELISTS 1 FRE
    ELIST GROUPS 1 BUFFER_POOL DEFAULT)
      TABLESPACE "USERS"  ENABLE
    PL/SQL procedure successfully completed.

  • How to convert CLOB to varchar2 whose length is more than 4000

    Hi ,
    I have to retrive the CLOB data into varchar2 and spilt those comma seperated values into rows
    but i am getting following error
    " ORA-06502: PL/SQL: numeric or value error: character string buffer too small "
    the proc i used is like following :
    : create table test_clob (grp_id CLOB, id number)
    Create or replace proc test_clob(p_id number )
    Is
    V_clob CLOB;
    V_str varchar2(4000);
    V_main varchar2(30000);
    TYPE t_clob IS REF CURSOR;
    cur_clob t_clob;
    Begin
    Select grp_id
    Into v_str
    From test_clob
    Where id= p_id;
    ---converting column data in rows as I have to return the cursor as output
    V_main:= ' select grp_id from ( WITH t AS
    (SELECT REGEXP_SUBSTR(''' || v_str ||
    ''', ''[^,]+'', 1, LEVEL) txt
    FROM DUAL
    CONNECT BY LEVEL <=
    LENGTH(''' || v_str ||
    LENGTH(REPLACE(''' || v_str ||
    ''', '','')) + 1)
    SELECT REGEXP_SUBSTR(trim(txt), ''[^\,]+'', 1, 1) grp_id
    FROM t )';
    open cur_clob for ' select rtrim(xmlagg(xmlelement(e, grp_id || '','')).extract (''//text()'').getclobval (),'','') grp_id
    from ( '|| v_main||' ) ';
    loop
    fetch cur_clob
    into V_clob;
    exit when cur_clob %notfound;
    end loop;
    insert into test_clob
    values (p_id, v_clob);
    commit;
    End;
    Please help its very urgent

    957624 wrote:
    Hi ,
    I have to retrive the CLOB data into varchar2 and spilt those comma seperated values into rows
    but i am getting following error
    " ORA-06502: PL/SQL: numeric or value error: character string buffer too small "
    the proc i used is like following :
    : create table test_clob (grp_id CLOB, id number)
    Create or replace proc test_clob(p_id number )
    Is
    V_clob CLOB;
    V_str varchar2(4000);
    V_main varchar2(30000);
    TYPE t_clob IS REF CURSOR;
    cur_clob t_clob;
    Begin
    Select grp_id
    Into v_str
    From test_clob
    Where id= p_id;
    ---converting column data in rows as I have to return the cursor as output
    V_main:= ' select grp_id from ( WITH t AS
    (SELECT REGEXP_SUBSTR(''' || v_str ||
    ''', ''[^,]+'', 1, LEVEL) txt
    FROM DUAL
    CONNECT BY LEVEL <=
    LENGTH(''' || v_str ||
    LENGTH(REPLACE(''' || v_str ||
    ''', '','')) + 1)
    SELECT REGEXP_SUBSTR(trim(txt), ''[^\,]+'', 1, 1) grp_id
    FROM t )';
    open cur_clob for ' select rtrim(xmlagg(xmlelement(e, grp_id || '','')).extract (''//text()'').getclobval (),'','') grp_id
    from ( '|| v_main||' ) ';
    loop
    fetch cur_clob
    into V_clob;
    exit when cur_clob %notfound;
    end loop;
    insert into test_clob
    values (p_id, v_clob);
    commit;
    End;
    Please help its very urgentNo, nothing is urgent here and it is very rude to suggest it is, as well as it being a breach of the terms of use for the forums. Urgent issues relate to commercially live systems, and for those you need to raise a support request with Oracle Support. The forums are manned by volunteers with their own jobs to do, so suggesting they drop everything to help you urgently is very rude. Also, other people asking questions would like answers to theirs as soon as possible too, so suggesting your question is more urgent than theirs is also rude to those people. You will find that suggesting your question is urgent will actually prevent people from helping you on the forums as many people will simply choose to ignore you for your rudeness (either that or they'll be rude back)
    Please read {message:id=9360002} to learn how to ask a question properly.
    Now, in answer to your question...
    What is it you are really trying to do?
    If you have comma seperated data, why it is being stored like that in a CLOB? That seems like bad design for storing data.
    If the data is coming from a file, then you could consider using External Tables (or SQL*Loader) to load the comma seperated data in a structured way.
    If you really have data in a clob in comma seperated format, what are you wanting to do with it exactly i.e. what determines where the data should be split?
    Your code isn't clear, but it looks like, on the one hand you are splitting comma seperated data out of a string, and on the other hand you're turning it into XML to get a clob of data back.
    Please be clear by providing some example data and expected output, along with your database version as explained in the FAQ post I linked to above.

  • How to convert clob to varchar2 in an update trigger

    Hi,
    I need to convert a field (clob) to varchar2 in a update trigger, how can I do that?
    regards.

    The maximum amount of data you can store in CLOB column is 4GB.
    You have table TABLE1 having col1 CLOB datatype.You have one more table
    Table_audit_1 without having CLOB datatype column and want to move CLOB
    data into VARCHAR2 column which has maximum length of 4000 and want to
    audit col1 CLOB into VARCHAR2.It seems to me you dont care about the data
    beyond 4000 bytes.
    In 9i SUBSTR, INSTR can be performed without reference to the DBMS_LOB
    package.
    SQL> DROP TABLE mytable
      2  /
    Table dropped.
    SQL> DROP TABLE mytable1
      2  /
    Table dropped.
    SQL> CREATE TABLE mytable
      2  (a   NUMBER,b   CLOB)
      3  /
    Table created.
    SQL> CREATE TABLE mytable1
      2  (c  NUMBER,d   VARCHAR2(4000))
      3  /
    Table created.
    SQL> DECLARE
      2      loc           CLOB;
      3  BEGIN
      4      FOR i IN 1..5000
      5      LOOP
      6        loc:=loc||i;
      7      END LOOP;
      8      INSERT INTO mytable  (a,b) VALUES (1,loc);
      9      INSERT INTO mytable1 (c,d) VALUES (1,SUBSTR(loc,1,4000));
    10      COMMIT;
    11  END;
    12  /
    PL/SQL procedure successfully completed.
    SQL> SET LONG 5000
    SQL> CREATE OR REPLACE TRIGGER mytrigger BEFORE UPDATE ON mytable FOR EACH ROW
      2  BEGIN
      3      UPDATE mytable1
      4         SET d=SUBSTR(:NEW.b,1,4000)
      5       WHERE c=:NEW.a;
      6  END;
      7  /
    Trigger created.
    SQL> DECLARE
      2      loc           CLOB;
      3  BEGIN
      4      FOR i IN 1..1000
      5      LOOP
      6        loc:=loc||'A '||i;
      7      END LOOP;
      8      UPDATE mytable
      9         SET b=loc
    10       WHERE a=1;
    11      COMMIT;
    12  END;
    13  /
    PL/SQL procedure successfully completed.
    SQL> SELECT LENGTH(b) FROM mytable
      2  /
    LENGTH(B)
          4893
    SQL> SELECT LENGTH(d) FROM mytable1
      2  /
    LENGTH(D)
          4000
    SQL> Khurram

  • Performance between CLOB and VARCHAR2

    I would like to know if there is any really performance issues between CLOB and VARCHAR2 data types?
    In particular, why would it not be better to declare all large text items as CLOB rather than VARCHAR2(4000) in a table? For example, if I am going to store about a page of text, in a table, why not standardize of CLOB? Only use VARCHAR2 for small text items.

    I doubt that there would be much, if any, performance difference between a CLOB and a VARCHAR2. By default, Oracle will store CLOBS directly in the table if they are less than about 4000 bytes, so the effect would be the same as a VARCHAR2(4000).
    The advantage of VARCHAR2(4000) over a CLOB is that you document and enforce the maximum size of the field. If you know that no test item will exceed 4000 bytes, then I would store it as a VARCHAR2, because if they can store more, someone will.
    A possible disadvantage of using CLOBS instead of VARCHAR2(4000) is that when you declare a column as a CLOB, Oracle creates the two lob segments whether or not they are needed to actually store data. So, depending on how many VARCHAR2(4000) columns you change to CLOBS without needing to store more than 4000 bytes, you can potentially waste a significant amount of space.
    SQL> CREATE TABLE t_clob (id NUMBER, descr CLOB);
    Table created.
    SQL> SELECT segment_name, index_name
      2  FROM dba_lobs
      3  WHERE table_name = 'T_CLOB';
    SEGMENT_NAME                   INDEX_NAME
    SYS_LOB0000136329C00002$$      SYS_IL0000136329C00002$$
    SQL> SELECT segment_name, segment_type, blocks
      2  FROM dba_segments
      3  WHERE segment_name in ('SYS_LOB0000136329C00002$$','SYS_IL0000136329C00002$$')
    SEGMENT_NAME                   SEGMENT_TYPE           BLOCKS
    SYS_IL0000136329C00002$$       LOBINDEX                   64
    SYS_LOB0000136329C00002$$      LOBSEGMENT                 64HTH
    John

  • Convert CLOB to VARCHAR2 in Oracle 8i

    Hello all,
    I would like to convert a CLOB column from a table to a VARCHAR2.
    How can I do this?
    I would like that this works in Oracle 8i, 9i and 10g.
    Thank you very much.

    Hello APC,
    I found the problem.
    I have Oracle Reports 6i + patch 17.
    The problem was that I couldn't select a CLOB column and store his value in a CLOB variable.
    I needed to do the conversion DBMS_LOB.SUBSTR in the select statement and store his value in a VARCHAR2 variable.
    Thank you

  • CLOB to VARCHAR2 conversion and limit of 8192 chars

    Hello, I have the folowing code which works on Oracle 10g SE but does not on XE:
    DECLARE
        d1 varchar2(32000);
    BEGIN
        d1 := to_char(substr(MY_FUNC_RETURNING_CLOB, 1, 8192));
    END;This ends with "ORA-06502: PL/SQL: numeric or value error." Only CLOBs shorter then 8192 works... (well the SUBSTR function is there just because of testing the maximum length of CLOB that does not fail).
    Is this my mistake, a bug in XE or some XE limitation (using UTF-8 version of XE)?
    Thanks for any hints!

    Well, it seem that conversion between CLOB and VARCHAR is done within UCS4 or something... Function MY_FUNC_RETURNING_CLOB returns SQL query (for subsequent EXECUTE IMMEDIATE command) and contains only ASCII characters and therefore should be 1char=1byte in UTF-8? I did a following workaround, which works pretty well for me (CLOBs are about 16000 chars long in my case)
    DECLARE
        d1 varchar2(32000);
        c1 varchar2(32000);
        c2 varchar2(32000);
        c3 varchar2(32000);
        c4 varchar2(32000);
    BEGIN
        c1 :=to_char(substr(MY_FUNC_RETURNING_CLOB, 0*8192, 8191));
        c2 :=to_char(substr(MY_FUNC_RETURNING_CLOB, 1*8192, 8191));
        c3 :=to_char(substr(MY_FUNC_RETURNING_CLOB, 2*8192, 8191));
        c4 :=to_char(substr(MY_FUNC_RETURNING_CLOB, 3*8192, 8191));
        d1 := c1 || c2 || c3 || c4;
    END;

  • Clob or varchar2 : help needed

    Hi all,
    I am using varchar2(8000) in my package.my lead wants me make it as a clob. Please advise.
    thanks
    kt

    It depends on what you are storing in your variable.
    In PL/SQL a varchar2 variable size can be up to 32K. But in SQL its just 4000 Bytes.
    So if you will store value which is less than 32K and you will have the scope just withing PL/SQL you can use a varchar2. But for any thing more than that you must go for CLOB.

  • Varchar2 to CLOB

    Hi,
    I want to convert my Varchar2 vairable to CLOB to store in my database is that any way to do so ?
    I have seen DBMS_LOB package but I dont understand how to use that . The DBMS_LOB package converts BFILE data to CLOB, so If any one knows how I can write intoa BFILE and then I can convert it to CLOB.
    Regards,
    Nishith Pancholi

    Hi!
    Here's a quick example for you:
    create table tmpl (f1 number, f2 clob);
    declare
    l_clob clob;
    l_str varchar2(32767) := 'asdf';
    begin
    insert into tmpl values (1, l_str);
    end;
    select * from tmpl;
    drop table tmpl;
    Regards,
    Andrew Velitchko
    BrainBench MVP for Developer/2000
    http://www.brainbench.com

  • Fetch VARCHAR2 from CLOB

    Hi,
    I have a plsql function which returns CLOB.(xml format)
    How do i convert the output CLOB to VARCHAR2 and select the function from a SELECT query.
    The returned output CLOB has more than 4000 characters.
    Using DBMS_LOB.SUBSTR only first 4000 characters are extracted , if we go for a larger value it gives a error.
    SELECT DBMS_LOB.SUBSTR((Getswiftmsgtagsappended_New(10,2,4,'SWIFT','103')),4000,1) FROM dual
    How to resolve this.
    Thanks.

    A-K wrote:
    Hi,
    Could you please tell as to what 'amount' and 'offset' mean in the following definition of dbms_lob.substr ?
    dbms_lob.substr(
    lob_loc IN CLOB CHARACTER SET ANY_CS,
    amount IN INTEGER := 32767,
    offset IN INTEGER := 1)
    RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;
    Thanks.amount=> how much
    offset=>from what position
    Example
    SQL> declare
      2          aclob clob;
      3          avc2 varchar2(32767);
      4  begin
      5          aclob:=lpad('X',32767,'X')||lpad('M',32767,'M');
      6          dbms_output.put_line('clob Len:'||dbms_lob.getlength(aclob));
      7          avc2:=dbms_lob.substr(aclob,4000,32767);
      8          dbms_output.put_line('Vc2 Len:'||length(avc2));
      9          dbms_output.put_line('Vc2 disp:'|| substr(avc2,1,50));
    10          avc2:=dbms_lob.substr(aclob,20,32767);
    11          dbms_output.put_line('Vc2 Len:'||length(avc2));
    12          dbms_output.put_line('Vc2 disp:'|| substr(avc2,1,50));
    13  end;
    14  /
    clob Len:65534
    Vc2 Len:4000
    Vc2 disp:XMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
    Vc2 Len:20
    Vc2 disp:XMMMMMMMMMMMMMMMMMMM
    PL/SQL procedure successfully completed.HTH
    SS

  • Using CLOB as a VARCHAR2 to write a string

    Hello everyone:
    I have this situation:
    After a query, i need to order the query rows in a table. To do this, i write a string using HTML format. Then, i send the string (message) by email, and i save the same in a table (database).
    The message, must be 32767 as a maximun number of characters. Because, the message is a VARCHAR2.
    When the number of characters is greater than 32767, in can't use this way.
    So, i trying to use a CLOB datatype, but i don't know how to write the string and then, send it by email.
    I wrote this code:
    xSGLOSA_UNO$ CLOB;
    xSGLOSA_UNO$ := '<table border="1"><tr>FECHA DE PROCESOS CORRECTAS</tr>';
    xSGLOSA_UNO$ := xSGLOSA_UNO$ || '<tr><td>Rut Operador</td><td>Nombre</td><td>Proceso</td><td>Fecha Proceso</td></tr>';
    BEGIN
    FOR CONSULTA_UNO IN(
    SELECT
    FPR_NRUTOPERADOR,
    OPE_SNOMBRE,
    FPR_SCODPROCESO,
    FPR_DFHOPROCESO
    FROM
    FECHAS_PROCESO,
    OPERADOR
    WHERE
    TRUNC(FPR_DFHOPROCESO) = TRUNC(SYSDATE)
    LOOP
    xSGLOSA_UNO$ := xSGLOSA_UNO$ ||  '<tr><td>' || CONSULTA_UNO.FPR_NRUTOPERADOR || '</td><td>' || CONSULTA_UNO.OPE_SNOMBRE || '</td><td>' || CONSULTA_UNO.FPR_SCODPROCESO || '</td><td>' || CONSULTA_UNO.FPR_DFHOPROCESO || '</td></tr>';
    END LOOP;
    xSGLOSA_UNO$ := xSGLOSA_UNO$ || '</table>';
    EXCEPTION
    WHEN OTHERS THEN
    NUMERROR$ := SQLCODE;
    MSJERROR$ := '[NES$FECHA_PROCESOS] FECHAS CORRECTAS (' || SQLERRM || ')';
    RETURN;
    END;
    And i have this error:
    [NUMERROR$:=-6502], [MSJERROR$:=[NES$FECHA_PROCESOS] FECHAS CORRECTAS (ORA-06502: PL/SQL: error  numérico o de valor)]
    Please, help me with this issue. I am new in Oracle, and i don't have idea the real reason for this.
    Thank you for support.

    Now... when you do things like:
    xSGLOSA_UNO$ := xSGLOSA_UNO$ || '</table>';
    then you are concatenating a CLOB (xSGLOSA_UNO$) to a VARCHAR2 ('</table>') which can be done by either convert the clob to varchar2 or the varchar2 to clob before concatenating. || is a overloaded function which accepts two varchar2 or two clob parameters (amongst others). As the CLOB gets bigger than 32k you cannot just let oracle decide how to convert so, you should do:
    xSGLOSA_UNO$ := xSGLOSA_UNO$ || TO_CLOB('</table>');
    instead.
    And this at every place where you concatenate
    eg here too:
    xSGLOSA_UNO$ := xSGLOSA_UNO$ || TO_CLOB('<tr><td>') || CONSULTA_UNO.FPR_NRUTOPERADOR || TO_CLOB('</td><td>') || CONSULTA_UNO.OPE_SNOMBRE || TO_CLOB('</td><td>') || CONSULTA_UNO.FPR_SCODPROCESO || TO_CLOB('</td><td>') || CONSULTA_UNO.FPR_DFHOPROCESO || TO_CLOB('</td></tr>');
    I don't know the datatypes of CONSULTA_UNO.FPR_NRUTOPERADOR and the other components used...if they are VARCHAR then convert, if they are CLOB then let them like they are.
    hth

  • Can not Load CLOB data 32k to target table

    SQL> DESC testmon1 ;
    Name Null? Type
    FILENAME VARCHAR2(200)
    SCANSTARTTIME VARCHAR2(50)
    SCANENDTIME VARCHAR2(50)
    JOBID VARCHAR2(50)
    SCANNAME VARCHAR2(200)
    SCANTYPE VARCHAR2(200)
    FAULTLINEID VARCHAR2(50)
    RISK VARCHAR2(5)
    VULNNAME VARCHAR2(2000)
    CVE VARCHAR2(200)
    DESCRIPTION CLOB
    OBSERVATION CLOB
    RECOMMENDATION CLOB
    SQL> DESC test_target;
    Name Null? Type
    LOCALID NOT NULL NUMBER
    DESCRIPTION NOT NULL CLOB
    SCANTYPE NOT NULL VARCHAR2(12)
    RISK NOT NULL VARCHAR2(6)
    TIMESTAMP NOT NULL DATE
    VULNERABILITY_NAME NOT NULL VARCHAR2(2000)
    CVE_ID VARCHAR2(200)
    BUGTRAQ_ID VARCHAR2(200)
    ORIGINAL VARCHAR2(50)
    RECOMMEND CLOB
    VERSION VARCHAR2(15)
    FAMILY VARCHAR2(15)
    XREF VARCHAR2(15)
    create or replace PROCEDURE proc1 AS
    CURSOR C1 IS
    SELECT FAULTLINEID,VULNNAME,scanstarttime, risk,
    dbms_lob.substr(DESCRIPTION,dbms_lob.getlength(DESCRIPTION),1) "DESCR",dbms_lob.substr(OBSERVATION,dbms_lob.getlength(OBSERVATION),1) "OBS",
    dbms_lob.substr(RECOMMENDATION) "REC",CVE
    FROM testmon1;
    c_rec C1%ROWTYPE;
    descobs clob;
    FSCAN_VULN_TRANS_REC VULN_TRANSFORM_STG%ROWTYPE;
    TIMESTAMP varchar2(50);
    riskval varchar2(10);
    pCTX PLOG.LOG_CTX := PLOG.init (pSECTION => 'foundscanVuln Procedure',
    pLEVEL => PLOG.LDEBUG,
    pLOG4J => TRUE,
    pLOGTABLE => TRUE,
    pOUT_TRANS => TRUE,
    pALERT => TRUE,
    pTRACE => TRUE,
    pDBMS_OUTPUT => TRUE);
    amount number;
    buffer varchar2(32000);
    BEGIN
    ---INITIALIZE THE LOCATOR FOR CLOB DATA TYPE
    select observation into descobs from testmon1 where rownum=1;
    OPEN C1;
    loop
    fetch C1 INTO c_rec;
    exit when C1%NOTFOUND;
    --LOAD THE DESCRIPTION FIELD FROM CURSOR AND WRITE IT TO THE CLOB LOCATOR descobs.
    dbms_lob.Write(descobs,dbms_lob(c_rec.DESCR),1,c_rec.DESCR);
    ------APPEND THE OBSERVATION FIELD FROM CURSOR TO THE CLOB LOCATOR descobs.
    dbms_lob.Writeappend(descobs,dbms_lob(c_rec.DESCR),c_rec.OBS);
    -- dbms_output.put_line ('the timestamp is :'||c_rec.scanstarttime);
    --dbms_lob.write(descobs,amount,1,buffer);
    descobs:=c_rec.OBS;
    --dbms_lob.read(descobs,amount,1,buffer);
    --dbms_lob.append(c_rec.DESCR,c_rec.OBS);
    --descobs:=c_rec.OBS;
    --dbms_output.put_line ('the ADDED DESCROBS is :'||dbms_lob.substr(c_rec.DESCR,dbms_lob.getlength(c_rec.DESCR),1));
    dbms_output.put_line ('the ADDED DESCRIPTION AND OBSERVATION is :'||descobs);
    --dbms_output.put_line ('the DESCROBS buffer  is :'||buffer);
    SELECT DESCRIPTION INTO FSCAN_VULN_TRANS_REC.DESCRIPTION
    FROM TESTMON1 WHERE ROWNUM=1;
    ---------LOAD THE DESCRIPTION+ observation value into the target table description
    DBMS_LOB.WRITE(FSCAN_VULN_TRANS_REC.DESCRIPTION, dbms_lob.getlength(descobs),1,descobs);
    TIMESTAMP:=substr(c_rec.scanstarttime,1,10)||' '|| substr(c_rec.scanstarttime,12,8);
    IF c_rec.risk <3
    THEN riskval:='Low';
    ELSIF c_rec.risk <6
    THEN riskval:='Medium';
    ELSIF c_rec.risk <10
    THEN riskval:='High';
    END IF;
    FSCAN_VULN_TRANS_REC.TIMESTAMP:=TO_DATE(TIMESTAMP, 'YYYY/MM/DD HH24:MI:SS');
    FSCAN_VULN_TRANS_REC.risk:= riskval;
    --dbms_lob.append(c_rec.DESCR,c_rec.OBS);
    FSCAN_VULN_TRANS_REC.DESCRIPTION:=c_rec.DESCR;
    FSCAN_VULN_TRANS_REC.RECOMMEND:=c_rec.REC;
    FSCAN_VULN_TRANS_REC.LocalID:=to_number(c_rec.FAULTLINEID);
    FSCAN_VULN_TRANS_REC.SCANTYPE:='FOUNDSCAN';
    FSCAN_VULN_TRANS_REC.CVE_ID:=c_rec.CVE;
    FSCAN_VULN_TRANS_REC.VULNERABILITY_NAME:=c_rec.VULNNAME;
    -- dbms_output.put_line ('the plog timestamp is :'||timestamp);
    -- dbms_output.put_line ('the timestamp is :'||riskval);
    --dbms_output.put_line ('the recommend is :'||FSCAN_VULN_TRANS_REC.RECOMMEND);
    --dbms_output.put_line ('the app desc is :'||FSCAN_VULN_TRANS_REC.DESCRIPTION);
    insert into test_target values FSCAN_VULN_TRANS_REC;
    End loop;
    close C1;
    commit;
    EXCEPTION
    WHEN OTHERS THEN
    -- dbms_output.put_line ('Data not found');
    -----------dbms_output.put_line (sqlcode|| ':'||sqlerrm);
    end proc1;
    using dbms_lob package is not helping. Either DB stops responding. Or the Observation field ( which has max length >300000) can not be loaed into a CLOB variable.
    Please help or give me a sample code that helps.

    select     
         BANKING_INSTITUTION.BANK_REF_CODE     C1_BANK_ID,
         BANKING_INSTITUTION.NAME_BANK     C2_BANK_NAME,
         BANKING_INSTITUTION.BANK_NUMBER     C3_BANK_NUMBER,
         BANKING_INSTITUTION.ISO_CODE     C4_GBA_CODE,
         BANKING_INSTITUTION.STATUS     C5_STATUS,
         BANKING_INSTITUTION.SOURCE     C6_SOURCE,
         BANKING_INSTITUTION.START_DATE_BANK     C7_START_DATE,
         BANKING_INSTITUTION.ADDRESS_BANK     C8_BANK_ADDRESS1
    from     REF_DATA_DB.BANKING_INSTITUTION BANKING_INSTITUTION
    where     (1=1)
    insert /*+ append */ into XXSVB.C$_0XXSVB_BANKS_STAGING
         C1_BANK_ID,
         C2_BANK_NAME,
         C3_BANK_NUMBER,
         C4_GBA_CODE,
         C5_STATUS,
         C6_SOURCE,
         C7_START_DATE,
         C8_BANK_ADDRESS1
    values
         :C1_BANK_ID,
         :C2_BANK_NAME,
         :C3_BANK_NUMBER,
         :C4_GBA_CODE,
         :C5_STATUS,
         :C6_SOURCE,
         :C7_START_DATE,
         :C8_BANK_ADDRESS1
    )

  • Clob datatype with pipelined table function.

    hi
    i made two functions one of them which use varchar2 data type with pipelined and
    another with clob data type with pipelined.
    i am giving parameters to both of them first varch2 with pipelined is working fine.
    but another is not.
    and i made diff type for both of them.
    like clob object type for second.
    and varchar2 type for first.
    my first function is like
    TYPE "CSVOBJECTFORMAT"  AS OBJECT ( "S"   VARCHAR2(500));
    TYPE "CSVTABLETYPE" AS TABLE OF CSVOBJECTFORMAT;
    CREATE OR REPLACE FUNCTION "FN_PARSECSVSTRING" (p_list
        VARCHAR2, p_delim VARCHAR2:=' ') RETURN CsvTableType PIPELINED
        IS
    l_idx PLS_INTEGER;
    l_list VARCHAR2(32767) := p_list;
    l_value VARCHAR2(32767);
    BEGIN
    LOOP
    l_idx := INSTR(l_list, p_delim);
    IF l_idx > 0 THEN
    PIPE ROW(CsvObjectFormat(SUBSTR(l_list, 1, l_idx-1)));
    l_list := SUBSTR(l_list, l_idx+LENGTH(p_delim));
    ELSE
    PIPE ROW(CsvObjectFormat(l_list));
    EXIT;
    END IF;
    END LOOP;
    RETURN;
    END fn_ParseCSVString;
    and out put for this function is like
    which is correct.
    SQL>   SELECT s  FROM  TABLE( CAST( fn_ParseCSVString('+588675,1~#588675^1^99^~2~16~115~99~SP5601~~~~~0~~', '~') as CsvTableType)) ;
    S
    +588675,1
    #588675^1^99^
    2
    16
    115
    99
    SP5601
    S
    0
    14 rows selected.
    SQL>
    my second function is like
    TYPE "CSVOBJECTFORMAT1"  AS OBJECT ( "S"   clob);
    TYPE "CSVTABLETYPE1" AS TABLE OF CSVOBJECTFORMAT1;
    CREATE OR REPLACE FUNCTION "FN_PARSECSVSTRING1" (p_list
        clob, p_delim VARCHAR2:=' ') RETURN CsvTableType1 PIPELINED
        IS
    l_idx PLS_INTEGER;
    l_list  clob := p_list;
    l_value VARCHAR2(32767);
    BEGIN
    dbms_output.put_line('hello');
      LOOP
      l_idx := INSTR(l_list, p_delim);
      IF l_idx > 0 THEN
    PIPE ROW(CsvObjectFormat1(substr(l_list, 1, l_idx-1)));
    l_list :=  dbms_lob.substr(l_list, l_idx+LENGTH(p_delim));
    ELSE
    PIPE ROW(CsvObjectFormat1(l_list));
    exit;
    END IF;
      END LOOP;
    RETURN;
    END fn_ParseCSVString1;
    SQL>   SELECT s  FROM  TABLE( CAST( fn_ParseCSVString1('+588675,1~#588675^1^99^~2~16~115~99~SP5601~~~~~0~~', '~') as CsvTableType1)) ;
    S
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    +588675,1
    and it goes on until i use ctrl+C to break it.
    actually i want to make a function which can accept large values  so i am trying to change first function.thanks

    RTFM DBMS_LOB.SUBSTR. Unlike built-in function SUBSTR, second parameter in DBMS_LOB.SUBSTR is length, not position. Also, PL/SQL fully supports CLOBs, so there is no need to use DBMS_LOB:
    SQL> CREATE OR REPLACE
      2  FUNCTION FN_PARSECSVSTRING1(p_list clob,
      3                              p_delim VARCHAR2:=' '
      4                             )
      5    RETURN CsvTableType1
      6    PIPELINED
      7    IS
      8        l_pos   PLS_INTEGER := 1;
      9        l_idx   PLS_INTEGER;
    10        l_value clob;
    11    BEGIN
    12        LOOP
    13          l_idx := INSTR(p_list, p_delim,l_pos);
    14          IF l_idx > 0
    15            THEN
    16              PIPE ROW(CsvObjectFormat1(substr(p_list,l_pos,l_idx-l_pos)));
    17              l_pos := l_idx+LENGTH(p_delim);
    18            ELSE
    19              PIPE ROW(CsvObjectFormat1(substr(p_list,l_pos)));
    20              RETURN;
    21          END IF;
    22        END LOOP;
    23        RETURN;
    24  END fn_ParseCSVString1;
    25  /
    Function created.
    SQL> SELECT rownum,s  FROM  TABLE( CAST( fn_ParseCSVString1('+588675,1~#588675^1^99^~2~16~115~99~SP5
    601~~~~~0~~', '~') as CsvTableType1)) ;
        ROWNUM S
             1 +588675,1
             2 #588675^1^99^
             3 2
             4 16
             5 115
             6 99
             7 SP5601
             8
             9
            10
            11
        ROWNUM S
            12 0
            13
            14
    14 rows selected.
    SQL> SY.

  • $200 reward to solve problem with JDBC and CLOB.getCharacterOutputStream

    I'm trying to update CLOB with the getCharacterOutputStream as suggested in the example code. It works with US7ASCII DB instance but not instances in UTF8.
    I've been browsing through all the Oracle doc's and found some rather confusing statements:
    In the page at http://oradoc.photo.net/ora816/java.816/a81354/oralob2.htm#1043220
    it says: [When writing to or reading from a CLOB, the JDBC drivers perform all character set conversions for you.]
    also: [The oracle.sql.CLOB class supports all the character sets that the Oracle data server supports for CLOB types.]
    So far so good.
    In the page at http://oradoc.photo.net/ora816/java.816/a81354/oraint3.htm#1012518
    it says [The oracle.sql package supports these datatypes in several ways: CLOBs point to large fixed-width character data items (that is, characters that require a fixed number of bytes per character) and are supported by the oracle.sql.CLOB class.]
    Ooh no! Is this for real? UTF8 is variable width and does this mean it is not supported?
    Any way to get around this?
    In the page at http://oradoc.photo.net/ora816/java.816/a81358/03_pub2.htm#36009
    says [6.The mappings to oracle.sql classes are optimal because they preserve data formats and require no character-set conversions (apart from the usual network conversions). Those classes are especially useful in applications that "shovel" data between SQL and Java.]
    "No character set conversion"? Very confusing!
    I've been hammering on this CLOB/JDBC/UTF8 problem for more than a week now and I really appreciate some solutions, workarounds, or whatever help I can get. I'm running java stored procedure in 8.1.6 on Linux RH6.2.
    For your trouble, I'd pay $200 for the first guy who come up with a verifiable solution.

    This is just findings based upon your comments:
    Please refer to document Oracle8i National Language Support Guide
    Release 2 (8.1.6) from Oracle Documentation Library, Release 8.1.7
    Chapter 6 Java,
    There its clearly mention that:
    "Oracle JDBC drivers provide globalization support by allowing users to retrieve data from or insert data into a database in any character set that Oracle supports. Because Java strings are UCS2 encoded (16-bit Unicode) for JDBC programs, the target character set on the client is always UCS2. Character set conversion is required to convert data from the database character set (Db Charset) to UCS2. This applies to CHAR, LONG, CLOB, and VARCHAR2 data types; RAW data is not converted. "
    Also..please refer this...
    "oracle.sql.CLOB's method getCharacterStream() returns the contents of a CLOB as a Unicode stream."
    "The techniques that Oracle's drivers use to perform character set conversion for Java applications depend on the character set the database uses. The simplest case is where the database uses a US7ASCII or WE8ISO8859P1 character set. In this case, the driver converts the data directly from the database character set to UCS2,which is used in Java applications. "
    "If you are working with databases that employ a non-US7ASCII or non-WE8ISO8859P1 character set (for example, Japanese or Korean), then the driver converts the data, first to UTF8, then to UCS2. "
    In my case the characte-set of the database is WE8ISO8859P1 and for security reason i can't change the character set but my feeling is that if you are updating the CLob from the java client you are forming a reference of a clob in the client which is UCS2 at the Java side. Now when you are populating the clob through java.io.Writer and call the procedure to pass the reference of the clob to the procedure then I believe the JDBC will convert the UCS2 datatype of Clob to UTF8 in the database.
    You can try out the code snippet:
    package ServletGDC;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import oracle.sql.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import ClassesGDC.*;
    public class testUpload extends HttpServlet {
    private String m_strMessage="";//It stores the message to be uploaded along with the Document
    Connection conn=null;
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    String strContent="";
    //res.setContentType("application/msword");
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    try {
    CallableStatement cmt=null;
    OutputStream output=null;
    ByteArrayOutputStream byteoutput=null;
    String strDocString="";
    oracle.sql.CLOB tempClob = null;
    String strPassedFileName="";     // the file name passed in the request object
    String strStdFilename="";//the file name to be given to the best practice
    String strSaveDirectory="";     //the directory in which the bp is to be saved
    String strParamName="";//name of parameters
    String strParamValue="";//value of parameters
    int intTempVariable=0; // temporaty variable
    long lngSizeOfFileUploaded=0;//stores the size of the file which had been uploaded in the file system
    File filePathOfFileUploaded=null;//stores the path of the file uploaded to the file system
    String strQuery="";
    //ST------------checks if the user has logged in or not-----------------------
    HttpSession session=req.getSession(true);
    if(req.getContentLength()>20*1024*1024)
    throw new skip("The size of the posted content is more than 10 MB . If you have a best practice whose size is more than 1 MB please mail it to Us.");
    byteoutput = new ByteArrayOutputStream();
    MultipartParser mp = new MultipartParser(req, 20*1024*1024); // 10MB is the limit of the file to be uploaded
    Part part;//Its an abstact part which helps in retrieving information about the file and the parameters
    while ((part = mp.readNextPart()) != null) {//Reads the next part
    strParamName = part.getName();
    // the following if is executed if the part is for a parameter rather than a file
    if (part.isParam()) {
    }else if (part.isFile()) {
    // it's a file part
    m_strMessage="inside file part";
    FilePart filePart = (FilePart) part;
    strPassedFileName = filePart.getFileName();
    strContent= filePart.getContentType();
    out.println("<BR><font color=red>strPassedFileName is "+strPassedFileName+"</font>");
    if(strPassedFileName != null || !(strPassedFileName.trim().equals("")) ) {
    // the part actually contained a file
    out.println("<BR><font color=red> before forming long</font>");
    //lngSizeOfFileUploaded = filePart.writeTo(filePathOfFileUploaded);      //the statement upload the bestpractice in the
    lngSizeOfFileUploaded = filePart.writeTo(byteoutput);     //specified file path filePathOfFileUploaded.
    out.println("<BR><font color=red> after file is written into the outputstream</font>");
    else {
    throw new skip("The file name is null or it is empty space. Files in such Format are not accepted");
    }//end of else if
    }//end of while loop
    if(     lngSizeOfFileUploaded==0)     {// the size of the file uploaded is zero then the file supplied was not proper and hence exception is to be thrown
    //if(filePathOfFileUploaded.exists())
    //     filePathOfFileUploaded.delete();
    throw new skip("The File could not be uploaded,Possible reasons may be that the file is sent null or the file is corrupted");
    //END---------------the file is uploaded in the proper directory--------------------
    //res.setContentType(strContent);
    out.println("<BR><font color=red>long value is : "+lngSizeOfFileUploaded+" and content is "+strContent+"</font>");
    String strbyte= byteoutput.toString();
    byteoutput.flush();
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // Establish network connection to database
    conn = DriverManager.getConnection("jdbc:oracle:thin:@pc-p32670:1521:GDCDBI","gdc_user","myuser");
    //if(conn!=null)
    out.println("<BR><font color=red>Connection formed"+conn);
    //els
    //out.println("<BR><font color=red>long value is : "+strbyte+"</font>");
    try{
    tempClob = oracle.sql.CLOB.createTemporary(conn,true, oracle.sql.CLOB.DURATION_SESSION);
    out.println("<BR><font color=red>tempClob : "+tempClob);
    tempClob.open( oracle.sql.CLOB.MODE_READWRITE);
    java.io.Writer tempClobWriter = tempClob.getCharacterOutputStream();
    // writing the string formed from the multipart file to the clob
    tempClobWriter.write(strbyte);
    if(tempClob!=null){}
    out.println("<BR><font color=red>CLOB value is : "+tempClob+"</font>");
    strQuery="{call INSERT_CLOB(?,?)}";
    cmt=conn.prepareCall(strQuery);
    cmt.setString(1,strPassedFileName);
    cmt.setClob(2,tempClob);
    cmt.registerOutParameter(2,java.sql.Types.CLOB);
    cmt.execute();
    tempClobWriter.flush();
    tempClobWriter.close();
    tempClob.freeTemporary();
    //res.setContentType(strContent);
    //strDocString.toString();
    out.println("<BR><font color=red>bob is "+strbyte+"</font>");
    tempClob.close();
    }catch(Exception e){
    tempClob.close();
    out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
    //e.printStackTrace(out);
    cmt.close();
    //out.println("<BR><font color=red><h2><b>SUCCESS</h2></font>");
    //res.sendRedirect("../test/showfile.jsp?contentype="+strContent.trim()+"");
    }catch(Exception e){
    java.util.Date d = new java.util.Date();
    String s =d.toString();
    out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
    //e.printStackTrace(out);
    }finally{
    try{
    if(conn!=null)
    conn.close();
    }catch(Exception e){
    out.println("<font color=blue> Error is :"+e.getMessage()+"</font>");
    }// end of finally
    } //end of doPost
    } //end of class
    in the Procedure you will be inserting/updating the clob in a table with the reference clob in the out parameter of the procedure
    Thanks.

Maybe you are looking for

  • When I enter a group name into the Bcc field and try to send the message, I get "[group name] is not a valid e-mail address..."

    Been using the same template to send a weekly newsletter for a year or two but now with a recent update to Thunderbird the group name is rejected when I try to send the message: With a group name in Bcc field, when I press "Send" and try to send the

  • Airport Extreme Base Station - Wireless AND Hardwired connections

    I have an Airport Extreme Base Station. I am under the impression that I can connect a hardwire via ethernet to my iMac, as well as use my wireless connections on my iBook. I am connected to the internet via my local Comcast Cable system on a SurfBoa

  • PR item level Release WorkFlow

    Hi Experts,                   I have activated PR item level release WorkFlow  WS00000038. My MM consultant has configured release strategy with ME51N. The Work flow works fine On releasing it sends notification work item to initator but on release R

  • FPGA Read/Write Control Issues

    Hello all!  Rather new to using FPGA, but I have an interesting issue that's popping up. Currently pulling in RAW voltage data from a set of sensors (Pressure Transducers, Load Cells, etc) through a cRIO DAQ.  Have the FPGA file setup to pull in that

  • Veritas Oracle Backup Failure "NEWFS_MAX_SERVER_CONNECTIONS"

    I am fairly new at Oracle administration so bear with me. We have been using Veritas Backup Exec (BE) 7.30 and the Oracle agent to backup an Oracle 8.1.5 db. This occurs nightly and has been successful for quite some time. In the last few days, howev