Convert CLOB to XMLType in SELECT statement ?

Hi XML Xperts,
In my Oracle 9.2.0.3 I have 1 table (tab1) with 2 cols (col1 as XMLType and col2 as CLOB). I Inserted in both fields the following same XML data :
<?xml version="1.0"?>
<TABLE_NAME>MY_TABLE</TABLE_NAME>
With the following statement, I can get the data from col1 which is a XMLType column :
SELECT a.col1.extract('//TABLE_NAME/text()').getStringVal() AS "Table Name"
FROM tab1 a
WHERE a.col1.existsNode('/TABLE_NAME') = 1;
How to get the same data FROM col2 whcih is a CLOB column ? Is it possible to transform the CLOB to XMLType in the SELECT statement ?
Note : I cannot change the type of the colulmn col2 to XMLType
Thanks in advance.
Phil

I tested it in 10g and it seems to be OK.
create table clobtoxml(xmldata clob);
insert into clobtoxml
values('<RootE><FirstNode>This is CLOB data to XML</FirstNode></RootE>');
commit;
select sys.xmltype(xmldata).extract('/RootE/FirstNode/text()').getStringVal() from clobtoxml;
This is CLOB data to XML
select sys.xmltype(xmldata).extract('/*') from clobtoxml;
<RootE>
<FirstNode>This is CLOB data to XML</FirstNode>
</RootE>
Ben

Similar Messages

  • Convert clob to xmltype

    Hi
    How to convert data CLOB datatype to XMLTYPE Datatype
    Ex: field col1 has clob data type
    any possible to convert col1 in target table col1 xmltype datatype
    Regards,
    Venkat

    Hi Venkat,
    Please try the following:
    CREATE TABLE CLOBTABLE (
    CLOBCOL1 CLOB
    INSERT INTO clobtable VALUES ('<?xml version="1.0"?> <EMP> <EMPNO>2</EMPNO> <ENAME>Sumeet</ENAME> </EMP>');
    CREATE OR REPLACE FUNCTION to_xmltype (clobcol CLOB) RETURN XMLTYPE AS
    BEGIN
    RETURN XMLType(clobcol);
    END;
    SELECT to_xmltype(clobcol) FROM clobtab;

  • How to convert CLOB to XMLType ??

    Hi,
    I created a table XML_TAB as
    SQL> desc xml_tab;
    Name Null? Type
    DOCID NUMBER
    DTD CLOB
    XMLDOC CLOB
    VALID NUMBER
    and I inserted a record in the table.
    Now the file inserted at the column XMLDOC, I want to convert it to XMLType. How can I do that.
    Some docs says to user XMLType.createXML function......
    But when I did it....................
    SQL> select xmltype.createxml(xmldoc) from xml_tab
    ERROR:
    ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00210: expected '<' instead of '<'
    Error at line 1
    ORA-06512: at "SYS.XMLTYPE", line 0
    ORA-06512: at line 1
    What could be the cause of the problem? Am I doing it in a correct way?
    -- Jitendra

    The main difference between CLOB and XMLType is that XMLType always contain a well formed XML document.
    So if CLOB doesn't complain , then XMLType does.

  • Convert NVARCHAR2 to VARCHAR2 in select statement

    I need to convert NVARCHAR2 values to VARCHAR2 in a select statement. Is this possible? The COUNTY_PARCEL_DATA colums are the NVARCHAR2 columns that need converting. I've tried TRANSLATE(COUNTY_PARCEL_DATA.SITUS_STREET_NUMBER USING CHAR_CS), CAST(COUNTY_PARCEL_DATA.SITUS_STREET_NUMBER AS VARCHAR2(100)), CONVERTCS(COUNTY_PARCEL_DATA.SITUS_STREET_NUMBER, 'CHAR_CS') and others directly in the statement for each column. Anything I'm missing? Thanks.
    SELECT BENEFICIARY.NAME_FIRST || ' ' || BENEFICIARY.NAME_LAST AS NAME,
    COUNTY_PARCEL_DATA.SITUS_STREET_NUMBER
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_DIRECTION
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_NAME
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_TYPE
    AS ADDRESS,
    COUNTY_PARCEL_DATA.SITUS_CITY AS CITY,
    'AZ' AS STATE,
    COUNTY_PARCEL_DATA.SITUS_ZIP AS ZIP,
    'T4' AS TRACER
    FROM BENEFICIARY
    LEFT OUTER JOIN
    VARS_PARCEL
    ON BENEFICIARY.AVNUM = VARS_PARCEL.AVNUM
    LEFT OUTER JOIN
    COUNTY_PARCEL_DATA
    ON VARS_PARCEL.APN = COUNTY_PARCEL_DATA.APN
    LEFT OUTER JOIN
    OWNER
    ON BENEFICIARY.BENEFICIARY_ID = OWNER.BENEFICIARY_ID
    WHERE (SUBSTR (VARS_PARCEL.AVNUM, 0, 4) IN
    (SELECT COLUMN_VALUE
    FROM TABLE(SPLIT_STRING (
    R_VARS_MAILING_NOTICES.NEIGHBORHOODS
    OR R_VARS_MAILING_NOTICES.NEIGHBORHOODS IS NULL)
    AND BENEFICIARY.BENEFICIARY_TYPE = 'Tenant';
    Edited by: Guddie on Apr 6, 2010 12:23 PM

    Are you doing the NVARCHAR2 to VARCHAR2 conversions everywhere, see comments below
    SELECT BENEFICIARY.NAME_FIRST || ' ' || BENEFICIARY.NAME_LAST AS NAME,
    COUNTY_PARCEL_DATA.SITUS_STREET_NUMBER                        <==== Here, obviously
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_DIRECTION                <==== Here
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_NAME                        <==== Here
    || ' '
    || COUNTY_PARCEL_DATA.SITUS_STREET_TYPE                        <==== Here
    AS ADDRESS,
    COUNTY_PARCEL_DATA.SITUS_CITY AS CITY,                            <==== Here
    'AZ' AS STATE,
    COUNTY_PARCEL_DATA.SITUS_ZIP AS ZIP,                                 <==== Here
    'T4' AS TRACER
    FROM BENEFICIARY
    LEFT OUTER JOIN
    VARS_PARCEL
    ON BENEFICIARY.AVNUM = VARS_PARCEL.AVNUM
    LEFT OUTER JOIN
    COUNTY_PARCEL_DATA
    ON VARS_PARCEL.APN = COUNTY_PARCEL_DATA.APN                   <==== Here, maybe not so obvious
    LEFT OUTER JOIN
    OWNER
    ON BENEFICIARY.BENEFICIARY_ID = OWNER.BENEFICIARY_ID
    WHERE (SUBSTR (VARS_PARCEL.AVNUM, 0, 4) IN
    (SELECT COLUMN_VALUE
    FROM TABLE(SPLIT_STRING (
    R_VARS_MAILING_NOTICES.NEIGHBORHOODS
    OR R_VARS_MAILING_NOTICES.NEIGHBORHOODS IS NULL)
    AND BENEFICIARY.BENEFICIARY_TYPE = 'Tenant';This is assuming that all fields in COUNTY_PARCEL_DATA are NVARCHAR2.
    Edited by: AlanWms on Apr 6, 2010 3:53 PM changed "joins" to "conversions" in 1st sentence.

  • XMLType.extract cannot show special French characters in select statement

    Hi,
    The (e acute) é characters get garbled when they are retrieved from the
    XMLType column of a regular table.
    How can we fix to get (e acute) é characters properly?
    We both tried setting "setenv NLS_LANG French_France.WE8ISO8859P1" and
    "setenv NLS_LANG French_France.WE8DEC" before loading the table.
    Database version:
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE    11.2.0.2.0      Production
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - ProductionThe sample test case is as follows:
    --connect to any schema where you can store XMLType
    set long 2000;
    set pagesize 2000;
    set serveroutput on;
    --delete from test;
    drop table test;
    create table test (id number, xmldata XMLType);
    declare
    featureDescriptorXML  CLOB;
    xml_type XMLType;
    new_xml_type XMLType;
    myName varchar2(100);
    myName2 varchar2(100);
    myName3 varchar2(100);
    stmt varchar2(4000);
    begin
    featureDescriptorXML :=
    '<?xml version="1.0" encoding="UTF-8"?>' ||
    '<abc:TheFeature xmlns:' || 'de' || '="' || 'http://abc.klmno.org/fghde' || '" xmlns:abc="http://www.ghijklmn.net/abc"' ||
    ' xmlns:xyz="http://www.ghijklmn.net/xyz">' ||
    '<abc:Name>de:MyGénérique</abc:Name>' ||
    '</abc:TheFeature>';
    xml_type := xmltype(featureDescriptorXML);
    myName := xml_type.extract('/abc:TheFeature/abc:Name/text()', 'xmlns:abc="http://www.ghijklmn.net/abc"').getStringVal();
    dbms_output.put_line('abc:Name value stored in VARCHAR2 variable from XMLType variable is ' || myName);
    -- can show French chars
    insert into test(id, xmldata) values(20, xml_type);
    stmt := 'select t.xmldata.extract(''/abc:TheFeature/abc:Name/text()'', ''xmlns:abc="http://www.ghijklmn.net/abc"'').getStringVal() from test t';
    execute immediate stmt into myName2;
    dbms_output.put_line('abc:Name value stored in VARCHAR2 variable from XMLType column in 2nd version is ' || myName2);
    -- cannot show French chars
    stmt := 'select  t.xmldata from test t';
    execute immediate stmt into new_xml_type;
    myName3 := new_xml_type.extract('/abc:TheFeature/abc:Name/text()', 'xmlns:abc="http://www.ghijklmn.net/abc"').getStringVal();
    dbms_output.put_line('abc:Name value stored in VARCHAR2 variable from first XMLType column and then from XMLType variable in 3rd version is ' || myName3);
    -- cannot show French chars
    end;
    select t.xmldata.extract('/abc:TheFeature/abc:Name/text()', 'xmlns:abc="http://www.ghijklmn.net/abc"').getStringVal()
    from test t;
    -- Cannot show French chars
    select t.xmldata.extract('/abc:TheFeature/abc:Name/text()', 'xmlns:abc="http://www.ghijklmn.net/abc"').getStringVal() "myname"
    from test t;
    -- Cannot show French chars
    select t.xmldata.getCLOBVal() from test t;
    -- Cannot show French chars
    select t.xmldata from test t;
    -- Can show French charsOutput is as follows with setenv NLS_LANG French_France.WE8ISO8859P1
    and NLS_DATABASE_PARAMETERS are as follows:
    SQL> select * from nls_database_parameters;
    PARAMETER                      VALUE
    NLS_LANGUAGE                   AMERICAN
    NLS_TERRITORY                  AMERICA
    NLS_CURRENCY                   $
    NLS_ISO_CURRENCY               AMERICA
    NLS_NUMERIC_CHARACTERS         .,
    NLS_CHARACTERSET               WE8DEC
    NLS_CALENDAR                   GREGORIAN
    NLS_DATE_FORMAT                DD-MON-RR
    NLS_DATE_LANGUAGE              AMERICAN
    NLS_SORT                       BINARY
    NLS_TIME_FORMAT                HH.MI.SSXFF AM
    PARAMETER                      VALUE
    NLS_TIMESTAMP_FORMAT           DD-MON-RR HH.MI.SSXFF AM
    NLS_TIME_TZ_FORMAT             HH.MI.SSXFF AM TZR
    NLS_TIMESTAMP_TZ_FORMAT        DD-MON-RR HH.MI.SSXFF AM TZR
    NLS_DUAL_CURRENCY              $
    NLS_COMP                       BINARY
    NLS_LENGTH_SEMANTICS           BYTE
    NLS_NCHAR_CONV_EXCP            FALSE
    NLS_NCHAR_CHARACTERSET         AL16UTF16
    NLS_RDBMS_VERSION              11.2.0.2.0
    20 ligne(s) sélectionnée(s).
    Table creé.
    abc:Name value stored in VARCHAR2 variable from XMLType variable is
    de:MyGénérique
    abc:Name value stored in VARCHAR2 variable from XMLType column in 2nd version is
    de:MyGénérique
    abc:Name value stored in VARCHAR2 variable from first XMLType column and then
    from XMLType variable in 3rd version is de:MyGénérique
    Procdure PL/SQL terminée avec succès.
    T.XMLDATA.EXTRACT('/ABC:THEFEATURE/ABC:NAME/TEXT()','XMLNS:ABC="HTTP://WWW.GHIJK
    de:MyGénérique
    myname
    de:MyGénérique
    T.XMLDATA.GETCLOBVAL()
    <?xml version="1.0" encoding="DEC-MCS"?>
    <abc:TheFeature xmlns:de="http://abc.klmno.org/fghde" xmlns:abc="http://www.ghij
    klmn.net/abc" xmlns:xyz="http://www.ghijklmn.net/xyz">
      <abc:Name>de:MyGénérique</abc:Name>
    </abc:TheFeature>
    XMLDATA
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <abc:TheFeature xmlns:de="http://abc.klmno.org/fghde" xmlns:abc="http://www.ghij
    klmn.net/abc" xmlns:xyz="http://www.ghijklmn.net/xyz">
      <abc:Name>de:MyGénérique</abc:Name>
    </abc:TheFeature>We also tried setting NLS_CHARACTERSET to AL32UTF8
    via ALTER DATABASE CHARACTER SET,
    and then shutting down the database and restarting it.
    But, that did not help.
    Thanks

    Good to hear then, you have not yet got a SR on your hands.
    One of the reasons I hate NLS issues is that me first one had to do with an client browser/ application server and database setup that involved not equal settings between the app.server and the database. Always, always fully check that the app.server (on all fronts) have the same NLS settings as the database so that you avoid unnecessary conversion between the middle tier and the database tier. "On all fronts" means, as I once painfully discovered, possible NLS settings in a registry, app.server configuration file, java application in the JVM, etc, etc, etc. Another issue is that JDBC drivers, AFAIK, have issues with "opaque data types" (http://en.wikipedia.org/wiki/Opaque_data_type) like "XMLTYPE" so, to be sure, I would advice to transport the "XML content" in a data type which is supported much longer like "CLOB". In such cases, NLS conversions shouldn't take place. There are exceptions of course, one I can think of right now is when you move Binary XML content via the binary xml transport method (can't remember right now the proper java classes to use for this) between the client and server to obtain performance gains due to among others less and more efficient data transport across the network and avoiding validation and post parse overhead during the Binary XML content handling in the database.
    Looked it up anyway :-) the following is part of the 11.2 Oracle XDK
    Binary XML usage with Java:
    http://download.oracle.com/docs/cd/E14072_01/appdev.112/e10708/adx_j_xmlbin.htm#BAJFBGGB
    Scalable DOM:
    http://download.oracle.com/docs/cd/E14072_01/appdev.112/e10708/adx_j_parser.htm#CCHGIADJ

  • [OCI] - Select statement on Clob doesn't return the full column's content.

    Hi All,
    I'm actually working on a application using OCI on an Oracle 11gr2. The Oracle client as the 11.2.0 version, was fully(admin) installed and configured with the same NLS_LANG variable as the DB.
    In the Database, we are using CLOB to store long text files. The setup our application was writing the initial CLOB correctly, but we cant read it, we just a part of the text.
    I checked it in SQLPlus and SQLDeveloper :
    select sourcecode from script where name like 'callback';
    result :
    SOURCECODE
    // #import "CallbackFctLib"
    * Benutzerdefinierte Funktionen bei der
    if I set the long to 1000 before the Select statement, then the full file is displayed.
    set long 1000;
    select sourcecode from script where name like 'callback';
    So, this works for SQLPlus and SQLDeveloper but how can I set it for the whole System? is ist possible? does any parameters have to be pass to the "sourcecode" column to define any format?
    thanks for reading...

    Hi!
    When you establish connection to database, try explicitly give instructions about what encoding use your DB, e.g.:
    // connection properties
    Properties connInfo = new Properties();
    connInfo.put("user", username);
    connInfo.put("password", password);
    connInfo.put("charSet", "Cp1251"); // enter your codepage!!!
    // getconnection
    Connection db = DriverManager.getConnection(dataurl, connInfo);

  • Convert sql select statement to oracle

    Hi All,
    Can anyone help me converting this Sql select statement to oracle ....
    -----------------------------------------Query--------------------------------------------------------------
    select emp_master.emp_code ,
    emp_master.dept_cd ,
    attendance_master.daily_attn_code ,
    attendance_master.linked_column ,
    case when location.payroll_status <> 'N' and eDocsNetEmployeesLeave.StartDate < dateadd(mm, 1 , convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01'))     
    then
    dateadd(mm, 1 , convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01'))
    when eDocsNetEmployeesLeave.StartDate < convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01')     
    then convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01') else eDocsNetEmployeesLeaveDetails.StartDate           
    end ,
    eDocsNetEmployeesLeaveDetails.NoOfDays,          
    case when eDocsNetEmployeesLeave.StartDate > location.next_pay_date     
    then convert(datetime , convert(varchar, dateadd(ss,-1, dateadd(mm, 1, convert(datetime , datename(yy,eDocsNetEmployeesLeave.StartDate)+ '/' + datename(mm,eDocsNetEmployeesLeave.StartDate)+ '/01') )),106) )     
    else      
    case when location.payroll_status <> 'N'
    then dateadd(mm,1,location.next_pay_date)      
    else location.next_pay_date
    end      
    end as PaymentDate               ,
    isnull(grade_master.leave_type,'C') ,
    eDocsNetEmployeesLeave.StartDate ,          
    eDocsNetEmployeesLeaveDetails.LeaveType
    from eDocsNetEmployeesLeave ,
    eDocsNetEmployeesLeaveDetails ,
    eDocsNetLeaveTypes ,
    emp_master ,
    grade_master ,
    attendance_master ,
    location
    where eDocsNetEmployeesLeaveDetails.RequestID     = eDocsNetEmployeesLeave.RequestID and
    eDocsNetEmployeesLeave.EmployeeID = emp_master.emp_code and
    eDocsNetEmployeesLeaveDetails.LeaveType = eDocsNetLeaveTypes.LeaveTypeID and
    eDocsNetLeaveTypes.loc_cd = emp_master.loc_cd and
    location.loc_cd = emp_master.loc_cd and
    attendance_master.loc_cd = emp_master.loc_cd and
    attendance_master.linked_column = eDocsNetLeaveTypes.LinkedAttendance and
    grade_master.loc_cd = emp_master.loc_cd and
    grade_master.grade_cd = emp_master.grade_cd and
    eDocsNetEmployeesLeaveDetails.RequestID      = @RequestID
    order by eDocsNetEmployeesLeaveDetails.StartDate
    Thanks in Advance
    Smiley

    Seems like you want to convert a SQL statement from the ??? dialect to the Oracle dialect. *(It would be useful to indicate the non-ANSI standard SQL you are starting with.)
    Part of the problem is that you use several date related functions. Some are unnecessary in Oracle and some need to translated into Oracle functions as found in the Functions section (chapter 5) of the SQL Reference manual at http://www.oracle.com/pls/db102/homepage
    Note that columns and expressions of type 'date' in ORacle always contain all of "yyyy mm dd hh mi ss" and you need to format and trauncate as necessary.
    Also note that '09-JAN-31' is NOT an Oracle date, but rather a character representation of a date which must be converted to/from a date expression. You will often need to use the to_date() and to_char() functions with a format mask as the second parameter. This is also descreibed in the first 2 chapters of the SQL Reference manual.

  • How to convert this select statement into update

    Hai All
    I have two table Namely Daily_attend , Train_mast
    Daily_attend Consist Of fields are Train_mast consist Of fields are
    Name varchar Train no var
    Empcode Num T_date date
    Intime Date Train_name var
    Outtime date Late_hrs var
    IND_IN Number
    IDE_OUT Number
    Attend_date date
    I need to update IDE_IN In Daily_attend table Depend upon late_hrs in the Train_mast table
    I have got Through in select statement This is my select statement
    select to_number(TO_DATE(TO_CHAR(Intime,'DD-MON-YYYY')||' '||
    TO_CHAR(0815,'0000'),'DD-MON-YYYY HH24:MI')+late_hrs/(24*60)-intime
    ) * 24*60 from dail_Att,train_mast;
    How can i convert it to update
    Any help is highly appricateable
    Thanks In Advance
    Regards
    Srikkanth.M

    Srikkanth,
    Try this code. And 1 more thing, i can't see any WHERE condition to join between the 2 tables DAIL_ATT, TRAIN_MAST.
    UPDATE DAIL_ATT A SET A.IDE_IN = (SELECT TO_NUMBER(TO_DATE(TO_CHAR(INTIME, 'DD-MON-YYYY')|| ' ' || TO_CHAR(0815, '0000'), 'DD-MON-YYYY HH24:MI') + LATE_HRS / (24 * 60) - INTIME) * 24 * 60 FROM TRAIN_MAST B WHERE <condition>);Regards,
    Manu.
    If my response or the response of another was helpful or Correct, please mark it accordingly

  • How to convert simple SQL Select statements into Stored Procedures?

    Hi,
    How can I convert following SELECT statement into a Stored Procedure?
    SELECT a.empno, b.deptno
    FROM emp a, dept b
    WHERE a.deptno=b.deptno;
    Thanking in advance.
    Wajid

    stored procedure is nothing but a named PL/SQL block
    so you can do it like this see below example
    SQL> create or replace procedure emp_details is
      2  cursor c1 is SELECT a.empno, b.deptno
      3  FROM scott.emp a, scott.dept b
      4  WHERE a.deptno=b.deptno;
      5  begin for c2 in c1
      6  LOOP
      7  dbms_output.put_line('name is '||c2.empno);
      8  dbms_output.put_line('deptno is ' ||c2.deptno);
      9  END LOOP;
    10  END;
    11  /
    Procedure created.and to call it use like below
    SQL> begin
      2  emp_details;
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SQL> set serveroutput on;
    SQL> /
    empno is 7839
    deptno is 10
    empno is 7698
    deptno is 30
    empno is 7782
    deptno is 10
    empno is 7566
    deptno is 20
    empno is 7654
    deptno is 30
    empno is 7499
    deptno is 30
    empno is 7844
    deptno is 30
    empno is 7900
    deptno is 30
    empno is 7521
    deptno is 30
    empno is 7902
    deptno is 20
    empno is 7369
    deptno is 20
    empno is 7788
    deptno is 20
    empno is 7876
    deptno is 20
    empno is 7934
    deptno is 10Edited by: Qwerty on Sep 17, 2009 8:37 PM

  • Select Statement - How do i convert rows to columns

    Hi, i need your help please.
    i have three options: A, B, C in table T_OPTIONS (not more and not less, it is always 3)
    no i can assign articles to this option.
    Article 1, 2, 3, 4
    in the table it looks like this
    ARTICLE_ID T_OPTIONS
    1                   A
    1                   B
    2                   C
    3                    A
    3                    C
    But now i want to have a select statement which convert rows to columns, it has to look like this
    ARTICLE A B C
    1             x x
    2             x
    3             x   x
    Can you help me!?
    Edited by: Dila on 02.08.2012 01:52
    Edited by: Dila on 02.08.2012 01:53

    Dila wrote:
    Hi, i need your help please.
    i have three options: A, B, C in table T_OPTIONS (not more and not less, it is always 3)
    no i can assign articles to this option.
    Article 1, 2, 3, 4
    in the table it looks like this
    ARTICLE_ID T_OPTIONS
    1                   A
    1                   B
    2                   C
    3                    A
    3                    C
    But now i want to have a select statement which convert rows to columns, it has to look like this
    ARTICLE A B C
    1             x x
    2             x
    3             x   x
    Can you help me!?
    Edited by: Dila on 02.08.2012 01:52
    Edited by: Dila on 02.08.2012 01:53Read {message:id=9360002} and {message:id=9360005}
    SQL> ed
    Wrote file afiedt.buf
      1  with sample_data as
      2  (
      3  select 1 ARTICLE_ID,'A' T_OPTIONS from dual union all
      4  select 1, 'B' from dual union all
      5  select 2, 'C' from dual union all
      6  select 3, 'A' from dual union all
      7  select 3, 'C' from dual
      8  )
      9   select article_id,
    10         decode(sum(case
    11                      when t_options = 'A' then 1
    12                      else 0
    13                    end), 0, null,
    14                          'X') A,
    15         decode(sum(case
    16                      when t_options = 'B' then 1
    17                      else 0
    18                    end), 0, null,
    19                          'X') B,
    20         decode(sum(case
    21                      when t_options = 'C' then 1
    22                      else 0
    23                    end), 0, null,
    24                          'X') C
    25  from   sample_data
    26* group  by article_id
    SQL> /
    ARTICLE_ID A B C
             1 X X
             2     X
             3 X   X

  • 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

  • Conversion of a Base64EncodedXML CLOB to XMLTYPE

    I have an xml file which is base64 encoded and the base64 encoded file is stored as a clob. I want to do all the manipulation in PL/SQL and modify the clob column with one of xmltype
    Heres the steps I've got so far:
    i) convert the clob to a blob using dbms_lob.converttoclob
    ii) Since this is now in binary format I'm asusming that I don't need to cast to raw
    iii) decode the binary file using UTL_ENCODE.base64_decode
    iv) add an additional column  temp_xml as type xml_type
    v) update the temp_xml column with the values of the original column.
    update <tablename>
                   set temp_xml = xmltype(orig_clob_column) vi) At this stage I will see if I can read the xml in the new column and if all is successful, I will drop the orig_clob_column and rename temp_xml to orig_clob_column.
    If I've missed anything or anyone's got some gotchas for me, it would be appreciated.
    Message was edited by:
    Keith Jamieson
    Message was edited by:
    Keith Jamieson

    I am using Oracle 11g Windows and based on the example here:
    http://www.peakretrieval.com/plsql/Chapter16/Convert.sql
    create or replace PROCEDURE CONVERT_ME (
       v_blob_or_clob IN NUMBER,
       v_blob IN OUT BLOB,
       v_clob IN OUT CLOB,
       v_amount IN OUT NUMBER,
       v_blob_offset IN OUT NUMBER,
       v_clob_offset IN OUT NUMBER,
       v_lang_context IN OUT NUMBER,
       v_warning OUT NUMBER)
    AS
    BEGIN
       DBMS_LOB.OPEN(v_blob, DBMS_LOB.LOB_READWRITE);
       DBMS_LOB.OPEN(v_clob, DBMS_LOB.LOB_READWRITE);
       IF v_blob_or_clob = 0
       THEN
       DBMS_LOB.CONVERTTOBLOB(v_blob,
                              v_clob,
                              v_amount,
                              v_blob_offset,
                              v_clob_offset,
                              1,
                              v_lang_context,
                              v_warning);
       ELSE
       DBMS_LOB.CONVERTTOCLOB(v_clob,
                              v_blob,
                              v_amount,
                              v_clob_offset,
                              v_blob_offset,
                              1,
                              v_lang_context,
                              v_warning);
       END IF;
       DBMS_LOB.CLOSE(v_blob);
       DBMS_LOB.CLOSE(v_clob);
    END;When I run this sample code
    DECLARE
       v_clob_or_blob NUMBER;
       v_blob_locator BLOB;
       v_clob_locator CLOB;
       v_blob_offset NUMBER;
       v_clob_offset NUMBER;
       v_lang_context NUMBER := DBMS_LOB.DEFAULT_LANG_CTX;
       v_warning NUMBER;
       v_string_length NUMBER(10);
       v_source_locator BLOB;
       v_destination_locator BLOB;
       v_amount PLS_INTEGER;
       v_string CLOB;
    BEGIN
       -- CONVERT CLOB TO BLOB
       SELECT description
       INTO v_clob_locator
       FROM book_samples
       WHERE book_sample_id = 1
       FOR UPDATE;
       SELECT misc
       INTO v_blob_locator
       FROM book_samples
       WHERE book_sample_id = 1
       FOR UPDATE;
       v_string_length := DBMS_LOB.GETLENGTH(v_blob_locator);
       v_amount := DBMS_LOB.GETLENGTH(v_clob_locator);
       DBMS_OUTPUT.PUT_LINE('The initial length of the BLOB is: '||v_string_length);
            v_clob_or_blob := 0; -- Convert clob to blob
            v_clob_offset := 1;
            v_blob_offset := 1;
            CONVERT_ME(v_clob_or_blob,
                    v_blob_locator,
                    v_clob_locator,
                    v_amount,
                    v_blob_offset,
                    v_clob_offset,
                    v_lang_context,
                    v_warning);
       v_string_length := DBMS_LOB.GETLENGTH(v_blob_locator);
       DBMS_OUTPUT.PUT_LINE('The length of the BLOB post-conversion is: '||v_string_length);
       -- COPY BLOB FOR ONE ROW TO BLOB IN ANOTHER
       v_source_locator := v_blob_locator;
       SELECT misc
       INTO v_destination_locator
       FROM book_samples
       WHERE book_sample_id = 2
       FOR UPDATE;
       DBMS_LOB.COPY(v_destination_locator, v_source_locator, 32768, 1, 1);
       v_string_length := DBMS_LOB.GETLENGTH(v_destination_locator);
       DBMS_OUTPUT.PUT_LINE('The length of the BLOB post-copy is: '||v_string_length);
       -- COPY BLOB FOR RECORD 2 BACK TO A CLOB
       SELECT description
       INTO v_clob_locator
       FROM book_samples
       WHERE book_sample_id = 2
       FOR UPDATE;
       SELECT misc
       INTO v_blob_locator
       FROM book_samples
       WHERE book_sample_id = 2
       FOR UPDATE;
       v_string_length := DBMS_LOB.GETLENGTH(v_clob_locator);
       v_amount := DBMS_LOB.GETLENGTH(v_blob_locator);
       DBMS_OUTPUT.PUT_LINE('The initial length of the CLOB (record 2) is: '||v_string_length);
            v_clob_or_blob := 1; -- Convert blob to clob
            v_clob_offset := 1;
            v_blob_offset := 1;
            CONVERT_ME(v_clob_or_blob,
                    v_blob_locator,
                    v_clob_locator,
                    v_amount,
                    v_clob_offset,
                    v_blob_offset,
                    v_lang_context,
                    v_warning);
       v_string_length := DBMS_LOB.GETLENGTH(v_clob_locator);
       SELECT description
       INTO v_string
       FROM book_samples
       WHERE book_sample_id = 2;
       DBMS_OUTPUT.PUT_LINE('The length of the CLOB post-conversion is: '||v_string_length);
       DBMS_OUTPUT.PUT_LINE('     ');
       DBMS_OUTPUT.PUT_LINE('The converted CLOB');
       DBMS_OUTPUT.PUT_LINE('==================');
       DBMS_OUTPUT.PUT_LINE(SUBSTR(v_string,1,150));
       DBMS_OUTPUT.PUT_LINE(SUBSTR(v_string,151,300));
    EXCEPTION
       WHEN OTHERS
       THEN
          DBMS_OUTPUT.PUT_LINE('I''M BROKEN ... FIX ME!');
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
    END;I get the following error:
    Length of blob before conversion
    The conver_me procedure is broken ...
    ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275
    Length of blob after conversion

  • Convert CLOB to a VARCHAR2

    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.
    If I try with dbms_lob.substr I don't know why the application crash.
    It says: 'RWRBE60.exe has generated errors and it will be closed for Windows'
    But if I don't use this command it works correctly.
    Any suggestion?
    Thank you very much.

    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 Vs XMLTYPE

    Hi Guys,
    In one of my applications , From the front end we are getting XML data and storing the xml data in the col of table which is CLOB type .
    Today one of the application developer told that directly we can store the xml data into the data base.Could any one tell me the difference in storing the data in the clob and xml
    and also what is the advantages of using xml over clob data type.
    Any suggestions will be highly appreciated.
    Thanks,
    Prafulla

    Prafulla wrote:
    Hi Guys,
    In one of my applications , From the front end we are getting XML data and storing the xml data in the col of table which is CLOB type .
    Today one of the application developer told that directly we can store the xml data into the data base.Could any one tell me the difference in storing the data in the clob and xml
    and also what is the advantages of using xml over clob data type.
    Any suggestions will be highly appreciated.
    Thanks,
    PrafullaXMLTYPE is based on the CLOB datatype under the hood. CLOB simply stores a whole stream of characters in one large chunk and you need to use the DBMS_LOB package to pull out any sort of structured information from that CLOB. XMLTYPE on the other hand understands that the content is XML and provides various methods for accessing the data as well as SQL being able to access the XML in a structured manner too.
    For example, if you have some XML in an XMLTYPE, you can use the XMLTABLE keyword in SQL to extract the data from it e.g..
    WITH t as (select XMLTYPE('
    <RECSET>
      <REC>
        <COUNTRY>1</COUNTRY>
        <POINT>1800</POINT>
        <USER_INFO>
          <USER_ID>1</USER_ID>
          <TARGET>28</TARGET>
          <STATE>6</STATE>
          <TASK>12</TASK>
        </USER_INFO>
        <USER_INFO>
          <USER_ID>5</USER_ID>
          <TARGET>19</TARGET>
          <STATE>1</STATE>
          <TASK>90</TASK>
        </USER_INFO>
      </REC>
      <REC>
        <COUNTRY>2</COUNTRY>
        <POINT>2400</POINT>
        <USER_INFO>
          <USER_ID>3</USER_ID>
          <TARGET>14</TARGET>
          <STATE>7</STATE>
          <TASK>5</TASK>
        </USER_INFO>
      </REC>
    </RECSET>') as xml from dual)
    -- END OF TEST DATA
    select x.country, x.point, y.user_id, y.target, y.state, y.task
    from t
        ,XMLTABLE('/RECSET/REC'
                  PASSING t.xml
                  COLUMNS country NUMBER PATH '/REC/COUNTRY'
                         ,point   NUMBER PATH '/REC/POINT'
                         ,user_info XMLTYPE PATH '/REC/*'
                 ) x
        ,XMLTABLE('/USER_INFO'
                  PASSING x.user_info
                  COLUMNS user_id NUMBER PATH '/USER_INFO/USER_ID'
                         ,target  NUMBER PATH '/USER_INFO/TARGET'
                         ,state   NUMBER PATH '/USER_INFO/STATE'
                         ,task    NUMBER PATH '/USER_INFO/TASK'
                 ) y
       COUNTRY      POINT    USER_ID     TARGET      STATE       TASK
             1       1800          1         28          6         12
             1       1800          5         19          1         90
             2       2400          3         14          7          5It uses XQuery expressions to reference the data, so you can reference attributes of the XML elements as well as their values, and you can also use namespaces if those are needed. The above is just a simple example with some nested repeating groups.
    If you tried to extract that data using a CLOB, you'd struggle to do that in SQL easily.

  • Re-use SELECT statement in several procedures (other than copy-and-paste)

    Our site uses a procedure of the following procedure construct to generate Excel spreadsheets:
    TYPE retCur is REF CURSOR;
    PROCEDURE get_data_for_excel (
      p_filter1 VARCHAR2
      ,p_filter2 VARCHAR2
      ,c_OutCursor out retCur
    IS
      retCursor retcur
    BEGIN
      BEGIN
      OPEN c_OutCursor FOR
        SELECT XMLELEMENT("TR", XMLFOREST(
           "col1" AS "TD"
           ,"col2" AS "TD"
           ,"col3" AS "TD"
          )).getstringval()DATA FROM (SELECT * FROM
       SELECT col1, col2, col3
       FROM sometable
       WHERE somecolumn = p_filter1
        AND someothercolumn = p_filter2
       ) x);
      END;
    END get_data_for_excel
    My question is, the subselect:
    SELECT col1, col2, col3
    FROM sometable
    is used in another procedure. Is there a way to reuse the select from the other procedure into this procedure so we don't copy-and-paste each time the other procedure is changed?
    Thanks a lot.

    This is a design decision you need to make BEFORE it goes into production.
    Right now you have
    procedure get_data_for_excel (
       p_filter1 VARCHAR2
      ,p_filter2 VARCHAR2
      ,c_OutCursor out retCur );
    What, I think jihuyao is trying to say is:  convert it to a pipelined function.
    I agree with jihuyao as I have ran into to this problem before.
    create type d4e_t as object ( DATA xmltype);
    create type d4e_table is table of d4e_t;
    create or replace function get_data_for_excel (
       p_filter1 VARCHAR2
      ,p_filter2 VARCHAR2 )
      return d4e_table pipelined;
    as
    begin
      for curr in ( --start of SELECT statement
    SELECT XMLELEMENT("TR", XMLFOREST(
           "col1" AS "TD"
           ,"col2" AS "TD"
           ,"col3" AS "TD"
          )).getstringval()DATA FROM (SELECT * FROM
       SELECT col1, col2, col3
       FROM sometable
       WHERE somecolumn = p_filter1
        AND someothercolumn = p_filter2
       ) x) )
    LOOP
      pipe row( d4e_t( curr.data ) );
    end loop;
    return;
    end;
    From there, you use it elsewhere as if it were a table.
    insert into t
    select X.data from table( get_data_for_excel( l_var1, l_var2 ) ) X;
    MK

Maybe you are looking for