XMLCast, XMLQuery vs extractValue

Hello fellows, newbie question - I am unable to find a working example to extract the values using the XMLQuery/XMLCast to replace the obsolete extractValue

Here is an XMLTYPE containing
< CalculateFITResponse xmlns = "http://tempuri.org/" >
< CalculateFITResult xmlns: a = "http://schemas.datacontract.org/2004/07/ValueNavigatorService.Classes" xmlns:i = "http://www.
w3.org/2001/XMLSchema-instance">
< a: VnSegments / >
< a: declineRate > 0 < / a: declineRate >
< a: entityId > 128041676 < / a: entityId >
< a: eur > 0 < / has: eur >
< a: historyVolume > 60000 < / a: historyVolume >
< a: results > FitSuccessful < / a: results >
< a: segmentData xmlns: b = "http://schemas.datacontract.org/2004/07/Eni.ValueNavigator.DeclineFitting" / >
< a: segmentDataList xmlns: b = "http://schemas.datacontract.org/2004/07/Eni.ValueNavigator.DeclineFitting" / >
< a: segmentVolume > 0 < / a: segmentVolume >
< / CalculateFITResult >
< / CalculateFITResponse >

This function-
Get_EUR_V_Results (CalculateFIT_OutputMessage IN XMLTYPE) RETURN of the FUNCTION to CREATE or REPLACE VARCHAR2
IS
V_Result VARCHAR2 (4000): = NULL;
l_ns_1 VARCHAR2 (4000): = ' xmlns: a = "http://schemas.datacontract.org/2004/07/ValueNavigatorService.Classes" ';
l_ns_2 VARCHAR2 (4000): = 'xmlns:i = "http://www.w3.org/2001/XMLSchema-instance" ';
l_ns_3 VARCHAR2 (4000): = 'xmlns = "http://tempuri.org/" ';
l_ns VARCHAR2 (4000): = l_ns_1 | l_ns_2 | l_ns_3;
l_xpath VARCHAR2 (4000): = ' / / CalculateFITResponse / / CalculateFITResult/a:';
BEGIN
SELECT extractValue (CalculateFIT_OutputMessage, l_xpath |) ("results, l_ns) IN V_Result of double;
RETURN V_Result;
END;
/

Returns FitSuccessful

(successfully I might add)

How to rewrite the function by using the XMLQuery and XMLCast?

(Yes, I RTFM with no progress)

Thanks in advance,

HKT

Hello

(Yes, I RTFM with no progress)

It's hard to believe...
I found this one in less than a minute in the documentation:
http://docs.Oracle.com/CD/E11882_01/AppDev.112/e23094/xdb_xquery.htm#BABIDFEC

And the forum is full of examples too, just use has research with XMLCast + XMLQuery, namespace keywords.

CREATE OR REPLACE FUNCTION get_EUR_V_Results (CalculateFIT_OutputMessage IN XMLTYPE) RETURN VARCHAR2
IS
  V_Result VARCHAR2(4000);
BEGIN
  SELECT XMLCast(
           XMLQuery(
           'declare default element namespace "http://tempuri.org/"; (: :)
            declare namespace a = "http://schemas.datacontract.org/2004/07/ValueNavigatorService.Classes"; (: :)
            /CalculateFITResponse/CalculateFITResult/a:results'
            passing CalculateFIT_OutputMessage
            returning content
           )
           as varchar2(4000)
         )
  INTO V_Result
  FROM dual;

  RETURN V_Result;
END;
/
SQL> select get_EUR_V_Results(xmltype('
  2  
  4  
  5  0
  6  128041676
  7  0
  8  60000
  9  FitSuccessful
 10  
 11  
 12  0
 13  
 14  '))
 15  from dual;

GET_EUR_V_RESULTS(XMLTYPE('

Tags: Oracle Development

Similar Questions

  • XMLQuery, XMLExists, XMLCast ORA-19276: XPST0005 invalid element

    My goal is to create relational views over XML data.
    I'm having trouble with the syntax XMLExists and XMLQuery.
    I work through the examples in the release of 11 g Oracle XML Developers Guide 2 (11.2) suitable for my schema and instance.
    The error is ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name:
    Any suggestions on how to navigate in the path of the item XMLExists, XMLQuery and XMLCast?
    It is a matter of follow-up to XML file too large or too large XML element
    PHARMA@scidev> select * from v$version;
    BANNER
    -------------------------------------------------------
    Oracle Database 11g 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 32-bit Windows: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    -The XMLDB is installed and running.
    VAR SCHEMAURL VARCHAR2(700)
    --
    begin
            :SCHEMAURL := 'http://lims.drugbank.ca/docs/drugbank.xsd';
    end;
    /
    
    DECLARE
        V_XMLSCHEMA XMLTYPE := xmltype(bfilename('XMLPHARMA', 'drugbank.xsd'),nls_charset_id('AL32UTF8'));
    BEGIN
            DBMS_XMLSCHEMA_ANNOTATE.disableDefaultTableCreation(V_XMLSCHEMA);
            DBMS_XMLSCHEMA_ANNOTATE.disableMaintainDOM(V_XMLSCHEMA);
            DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'BondType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'references','CLOB',TRUE);
            DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'PartnerType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'references','CLOB',TRUE);
            DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'DrugType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'general-references','CLOB',TRUE);
            DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'SequenceType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'chain','CLOB',TRUE);
    
           DBMS_XMLSCHEMA.registerSchema(
              SCHEMAURL => :SCHEMAURL,
              SCHEMADOC => V_XMLSCHEMA,
              LOCAL     => TRUE,
              GENTYPES  => TRUE,
              GENTABLES => TRUE);
    END;
    / 
    
    CREATE TABLE drugs_xmltype OF XMLTYPE
      XMLSCHEMA "http://lims.drugbank.ca/docs/drugbank.xsd"
      ELEMENT "drugs"
    /
    
    SELECT table_name FROM user_xml_tables;
    TABLE_NAME
    ------------------------------
    DRUGS_XMLTYPE
    1 row selected.
    SELECT COUNT(*) FROM user_nested_tables;
           COUNT(*)
    ---------------
                 36
    1 row selected.
    
    INSERT INTO drugs_xmltype
    VALUES(XMLType(bfilename('XMLPHARMA', 'drugbank.xml'),nls_charset_id('AL32UTF8')))
    ;
    1 row created.
    commit;
    Commit complete.
    
    desc drugs_xmltype
     Name                                                                          Null?    Type
     ----------------------------------------------------------------------------- -------- ----------------------------------------------------
    TABLE of SYS.XMLTYPE(XMLSchema "http://lims.drugbank.ca/docs/drugbank.xsd" Element "drugs") STORAGE Object-relational TYPE "drugs1609_T"
    
    BEGIN 
                  DBMS_STATS.GATHER_SCHEMA_STATS (
                    ownname => 'PHARMA',
              estimate_percent => 100
              );
    END;
    /
    generated by XMLDB schema document
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" targetNamespace="http://drugbank.ca" xmlns="http://drugbank.ca" elementFormDefault="qualified" attributeFormDefault="unqualified" xdb:storeVarrayAsTable="true" xdb:flags="2105639" xdb:schemaURL="http://lims.drugbank.ca/docs/drugbank.xsd" xdb:schemaOwner="PHARMA" xdb:numProps="177">
    ...snip
      <xs:complexType name="DrugType" xdb:maintainDOM="false" xdb:SQLType="DrugType1543_T" xdb:SQLSchema="PHARMA">
        <xs:sequence>
          <xs:element name="drugbank-id" type="xs:string" xdb:propNumber="5488" xdb:global="false" xdb:SQLName="drugbank-id" xdb:SQLType="VARCHAR2" xdb:memType="1" xdb:MemInline="true" xdb:SQLInline="true" xdb:JavaInline="true"/>
          <xs:element name="name" type="xs:string" xdb:propNumber="5489" xdb:global="false" xdb:SQLName="name" xdb:SQLType="VARCHAR2" xdb:memType="1" xdb:MemInline="true" xdb:SQLInline="true" xdb:JavaInline="true"/>
    ...snip
      <xs:element name="drugs" xdb:defaultTable="" xdb:propNumber="5446" xdb:global="true" xdb:SQLName="drugs" xdb:SQLType="drugs1609_T" xdb:SQLSchema="PHARMA" xdb:memType="258" xdb:defaultTableSchema="PHARMA">
        <xs:complexType xdb:maintainDOM="false" xdb:SQLType="drugs1609_T" xdb:SQLSchema="PHARMA">
          <xs:sequence>
            <xs:element name="drug" type="DrugType" minOccurs="0" maxOccurs="unbounded" xdb:propNumber="5443" xdb:global="false" xdb:SQLName="drug" xdb:SQLType="DrugType1543_T" xdb:SQLSchema="PHARMA" xdb:memType="258" xdb:MemInline="false" xdb:SQLInline="true" xdb:JavaInline="false" xdb:SQLCollType="drug1610_COLL" xdb:SQLCollSchema="PHARMA"/>
    document instance
    <drugs xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" 
              xmlns="http://drugbank.ca" 
              xs:schemaLocation="http://drugbank.ca http://lims.drugbank.ca/docs/drugbank.xsd">
      <drug type="biotech" created="2005-06-13 07:24:05 -0600" version="3.0" updated="2010-11-25 15:36:58 -0700">
        <drugbank-id>DB00001</drugbank-id>
    ...snip
    XMLTable works closely with XMLNamespaces to 1 row by drugs, tables nested with fields and tables nested with a single field
    the XMLNamespaces with example is based off of this thread create a relational view received the error: ORA-19276: XPST0005 - XPath step Brown
    CREATE OR REPLACE VIEW pharma.drugs_vw AS
    SELECT d.*
    FROM drugs_xmltype dx, XMLTable(XMLNamespaces(default 'http://drugbank.ca'), 
        '/drugs/drug' 
        PASSING dx.OBJECT_VALUE COLUMNS
        drugbank_id        VARCHAR2(20)   PATH 'drugbank-id',
        drug_name               VARCHAR2(50)   PATH 'name',
        description        VARCHAR2(4000) PATH 'description',
        cas_number         VARCHAR2(20)   PATH 'cas-number',
        general_references VARCHAR2(4000) PATH 'general-references',
        synthesis_reference VARCHAR2(4000) PATH 'synthesis-reference',
        indication         VARCHAR2(4000) PATH 'indication',
        pharmacology       VARCHAR2(4000) PATH 'pharmacology',
        mechanism_of_action VARCHAR2(4000) PATH 'mechanism-of-action',
        toxicity            VARCHAR2(4000) PATH 'toxicity',
        biotransformation   VARCHAR2(4000) PATH 'biotransformation',
        absorption          VARCHAR2(4000) PATH 'absorption',
        half_life           VARCHAR2(4000) PATH 'half-life',
        protein_binding     VARCHAR2(4000) PATH 'protein-binding',
        route_of_elimination VARCHAR2(4000) PATH 'route-of-elimination',
        volume_of_distribution VARCHAR2(4000) PATH 'volume-of-distribution',
        clearance           VARCHAR2(4000) PATH 'clearance'    
    ) d
    ORDER BY d.drugbank_id
    ;
    
    PHARMA@scidev> select drugbank_id, drug_name from drugs_vw where rownum <= 5;
    
    DRUGBANK_ID          DRUG_NAME
    -------------------- --------------------------------------------------
    DB00001              Lepirudin
    DB00002              Cetuximab
    DB00003              Dornase Alfa
    DB00004              Denileukin diftitox
    DB00005              Etanercept
    
    5 rows selected.
    Elapsed: 00:00:00.89
    
    CREATE OR REPLACE VIEW pharma.packager_vw AS
    SELECT dt.drugbank_id, dt.cas_number, pack.*
    FROM drugs_xmltype dx, 
        XMLTABLE(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '/drugs/drug' 
                PASSING dx.OBJECT_VALUE COLUMNS
                    drugbank_id        VARCHAR2(20)   PATH 'drugbank-id',
                    cas_number         VARCHAR2(20)   PATH 'cas-number',
                    packager XMLTYPE PATH 'packagers/packager') dt,
        XMLTABLE(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '/packager' 
                PASSING dt.packager COLUMNS 
                    packager_name VARCHAR2(30) PATH 'name',
                    packager_url VARCHAR2(30) PATH 'url') pack
    ORDER BY dt.drugbank_id
    ;
    
    PHARMA@scidev> select drugbank_id, packager_name from packager_vw where rownum <= 5;
    
    DRUGBANK_ID          PACKAGER_NAME
    -------------------- ------------------------------
    DB00001              Bayer Healthcare
    DB00001              Berlex Labs
    DB00002              Cardinal Health
    DB00002              ImClone Systems Inc.
    DB00002              Catalent Pharma Solutions
    
    
    CREATE OR REPLACE VIEW pharma.secondary_accession_number_vw AS
    SELECT dt.drugbank_id, dt.cas_number, sa.*
    FROM drugs_xmltype dx, 
        XMLTABLE(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '/drugs/drug' 
                PASSING dx.OBJECT_VALUE COLUMNS
                    drugbank_id        VARCHAR2(20)   PATH 'drugbank-id',
                    cas_number         VARCHAR2(20)   PATH 'cas-number',
                    secondary_accession_number XMLTYPE PATH 'secondary-accession-numbers/secondary-accession-number') dt,
        XMLTABLE(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '/secondary-accession-number' 
                PASSING dt.secondary_accession_number COLUMNS
                    secondary_accession_number VARCHAR2(20) PATH '/') sa
    ORDER BY dt.drugbank_id
    ;
    PHARMA@scidev> select drugbank_id, secondary_accession_number from secondary_accession_number_vw where rownum <= 5;
    
    DRUGBANK_ID          SECONDARY_ACCESSION_
    -------------------- --------------------
    DB00001              BTD00024
    DB00001              BIOD00024
    DB00002              BTD00071
    DB00002              BIOD00071
    DB00003              BTD00001
    
    5 rows selected.
    Elapsed: 00:00:00.34
    Copy the following code generates error
    ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drugs)
    SELECT OBJECT_VALUE
    FROM drugs_xmltype
    WHERE XMLExists('/drugs/drug[drugbank-id="DB00001"]' PASSING OBJECT_VALUE);
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drug)
    SELECT OBJECT_VALUE
    FROM drugs_xmltype
    WHERE XMLExists('/drug[drugbank-id="DB00001"]' PASSING OBJECT_VALUE);
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drug)
    SELECT OBJECT_VALUE
    FROM drugs_xmltype
    WHERE XMLExists('drug[drugbank-id="DB00001"]' PASSING OBJECT_VALUE);
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drugs)
    SELECT XMLQuery('/drugs/drug/drugbank-id' 
        PASSING OBJECT_VALUE RETURNING CONTENT)
    FROM drugs_xmltype;
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (XMLDATA)
    SELECT XMLQuery('/XMLDATA/drug/drugbank-id' 
        PASSING OBJECT_VALUE RETURNING CONTENT)
    FROM drugs_xmltype;
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drugs)
    SELECT XMLCast(XMLQuery('/drugs/drug/drugbank-id' PASSING OBJECT_VALUE RETURNING CONTENT)
                AS VARCHAR2(10)) "DBID"
    FROM drugs_xmltype;
    
    -- ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name: (drug)
    SELECT XMLCast(XMLQuery('/drug/drugbank-id' PASSING OBJECT_VALUE RETURNING CONTENT)
                AS VARCHAR2(10)) "DBID"
    FROM drugs_xmltype;
    
    -- here the XMLTable works (returns the whole XML file), but the XMLExists fails
    -- ORA-00936: missing expression on the DEFAULT, which is a reserved word
    -- I assume that XMLNamespaces is not allowed for XMLExists. 
    SELECT dbid.COLUMN_VALUE
    FROM drugs_xmltype dx, XMLTABLE(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '/drugs/drug' 
        PASSING dx.OBJECT_VALUE) dbid
    WHERE XMLEXISTS(XMLNamespaces(DEFAULT 'http://drugbank.ca'), '$d/drugs/drug[drugbank-id="DB00014"]' PASSING OBJECT_VALUE as "d");
    ;

    Namespace declarations...

    See example here xmlexists: Namespace in XMLEXISTS statement

  • using XPath with SQL to extract XML data

    Given the data like this:
    <?xml version="1.0"?>
    <ExtendedData>
       <Parameter name="CALLHOLD"><BooleanValue>true</BooleanValue></Parameter>
    
      <Parameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="BARRING_PASSWORD" xsi:nil="true"/>
    
      <Parameter name="ALLCF"><BooleanValue>true</BooleanValue></Parameter>
    
      <Parameter name="RealProv"><BooleanValue>false</BooleanValue></Parameter>
    
    </ExtendedData>
    I usually use extractValue as shown below, for example function to extract the value for the last parameter in the above data, for example:
    select extractValue(extended_data,'/ExtendedData/Parameter[@name="RealProv"]/BooleanValue') "my_column_alias" from table
    Any ideas on how can I return the value of the parameter xsi: Nil for that node:
    <Parameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="BARRING_PASSWORD" xsi:nil="true"/>
    I would like to extract the
    true
    in
    xsi:nil="true"
    ...

    Thank you

    Published by: HouseofHunger on May 15, 2012 14:13

    Published by: HouseofHunger on May 15, 2012 14:13

    ExtractValue() has a third parameter, that we can use to declare the namespace mappings:

    SQL> with sample_data as (
      2    select xmltype('
      3  
      4    true
      5    
      6    true
      7    false
      8  ') doc
      9    from dual
     10  )
     11  select extractvalue(
     12           doc
     13         , '/ExtendedData/Parameter[@name="BARRING_PASSWORD"]/@xsi:nil'
     14         , 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
     15         )
     16  from sample_data
     17  ;
    
    EXTRACTVALUE(DOC,'/EXTENDEDDAT
    --------------------------------------------------------------------------------
    true
     
    

    If you are on 11.2.0.2 and upward, extractvalue() is obsolete.
    Must use XMLCast/XMLQuery instead:

    SQL> with sample_data as (
      2    select xmltype('
      3  
      4    true
      5    
      6    true
      7    false
      8  ') doc
      9    from dual
     10  )
     11  select xmlcast(
     12           xmlquery('/ExtendedData/Parameter[@name="BARRING_PASSWORD"]/@xsi:nil'
     13            passing doc
     14            returning content
     15           ) as varchar2(5)
     16         )
     17  from sample_data
     18  ;
    
    XMLCAST(XMLQUERY('/EXTENDEDDAT
    ------------------------------
    true
     
    

    Note: the prefix xsi is predefined when using Oracle's XQuery, so in this case we must explicitly declare.

    Published by: odie_63 on May 15, 2012 15:23

  • Retrieve / search a specific node of the XML file

    Hello

    I have a question about reading the XML (search) in PL SQL file:

    There is an XML file with the following structure:
    <root>
      <Hnode1 attr1="value1" />
      <Hnode2 attr1="value1" /> 
         <node1_of_Hnode2 id="10" personname="Steven"/>
         <node2_of_Hnode2 id="20" personname="Christian"/>
         <node3_of_Hnode2 id="30" personname="Arnold"/>
         .
         .
      <Hnode2/>
    <root/>
    How it is possible to filter a node by one of its attribute value. For example:
    The id of a person - I guess that id = 20. In this case I would like to get the whole node (in this case node2_of_Hnode2) to get the personname = > 'Christian '.
    Just like a SELECT statement (WHERE ID = 20)

    Is it possible to get it in a single order or should it be buckled on all the lines in the Document. Can you please provide an example for me.

    Thank you for advice!

    The basic version is 10.

    Sorry, this is not a version.
    For example:

    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    PL/SQL Release 10.2.0.5.0 - Production
    CORE     10.2.0.5.0     Production
    TNS for 64-bit Windows: Version 10.2.0.5.0 - Production
    NLSRTL Version 10.2.0.5.0 - Production
     
    

    The use of the extraction of the values?
    1. better in a Select statement. assignment directli in a variable, or by using the xmlquery function?

    PL/SQL or SQL calls to the XMLType methods such as getStringVal() or extract() function should be equivalent (save the change of context).
    However, none of them are the right way to retrieve a scalar value of a given node.
    You must use the rather extractValue() function (SQL only) for immediate release< 11.2="" and="" xmlcast/xmlquery="" starting="" with="">

    Another Question:

    I've seen a lot of options for dealing with XML files.

    In my case only query data in XML files is relevant.

    I've seen to many API called XMLDOM, DMBS_XMLDOM, XMLTYPE...

    When to use these APIs. Can you give me feedback on this please?

    It is a broad topic.
    An appropriate response will depend on your condition.

    -You have to deal with large files and if so what size?
    -Performance/memory management is a concern for you?
    -You want to extract unique values or process the XML content in the form of relational data?

    If you have any specific test cases to show us, please post in the {forum: id = 34} forum and make sure to include all the necessary details (see the FAQ).

    Published by: odie_63 on 23 Feb. 2012 11:35

  • Cannot retrieve the data by binary storage by default for XML 11 g

    Oracle 11.2

    All,

    As someone mentioned in another post, I got I should use binary XMLType CLOB rather than 11g because it is more efficient. When I create the XMLType column as binary I can't retrieve the value of the column, but when I use CLOB I am able to extract data on.

    -Create table with XMLTYPE column.  Since it is 11.2 storage of the column is automatically binary
    CREATE THE TABLE HR. XMLTABLESTORE (key_id VARCHAR2 (10) PRIMARY KEY, xmlloaddate date, xml_column XMLTYPE);

    -Insert the XML into the XML column
    INSERT INTO HUMAN RESOURCES. VALUES XMLTABLESTORE (HR. XMLSEQUENCE. NEXTVAL, SYSDATE, XMLType (bfilename ('XMLDIRX', 'PROD_20110725_211550427_220b.xml'),
    nls_charset_id ('AL32UTF8'))); COMMIT;

    -When I do a select I see full XML in the xml_column column
    SELECT * FROM HR. XMLTABLESTORE

    -When I run the following query I get the following:
    SELECT extract (xml_column, ' / / MapItem/@ProductNum') ProductNum OF HR. XMLTABLESTORE

    ProductNum
    -------------
    XMLType

    -When I run the following query on the @, I get the following:
    SELECT extract (xml_column, ' / / MapItem/ProductNum ') ProductNum OF HR. XMLTABLESTORE

    ProductNum
    -------------
    Null value

    When I run the same SELECT query retrieves (xml_column, ' / / MapItem/@ProductNum') ProductNum OF HR. XMLTABLESTORE and the table is created by CLOB, I get out the expected value of the XML file.

    How can I get the query to retrieve the data through a binary file?

    I appreciate any help in advance.

    Thank you
    Shawn

    Published by: 886184 on Sep 20, 2011 15:42

    Probably a problem with your client tool.

    It works for me:

    SQL*Plus: Release 11.2.0.2.0 Beta on Mer. Sept. 21 19:39:55 2011
    
    Copyright (c) 1982, 2010, Oracle.  All rights reserved.
    
    Connected to:
    Oracle Database 11g Express Edition Release 11.2.0.2.0 - Beta
    
    SQL> CREATE TABLE xmltablestore (
      2    key_id VARCHAR2(10) PRIMARY KEY
      3  , xmlloaddate DATE
      4  , xml_column XMLTYPE
      5  );
    
    Table created.
    
    SQL> INSERT INTO xmltablestore
      2  VALUES ('1', sysdate, XMLType(bfilename('TEST_DIR', 'PROD_20110725_211550427_220b.xml'),nls_charset_id('AL32UTF8')))
      3  ;
    
    1 row created.
    
    SQL> commit;
    
    Commit complete.
    
    SQL> SELECT extract(xml_column, '//MapItem/@ProductNum') ProductNum
      2  FROM xmltablestore
      3  ;
    
    PRODUCTNUM
    --------------------------------------------------------------------------------
    63481062975
    
    SQL> SELECT extractValue(xml_column, '//MapItem/@ProductNum') ProductNum
      2  FROM xmltablestore
      3  ;
    
    PRODUCTNUM
    --------------------------------------------------------------------------------
    63481062975
    
    SQL> SELECT xmlcast(
      2          xmlquery('/Entries/Category/MapItem/@ProductNum'
      3           passing t.xml_column
      4           returning content
      5          )
      6          as number
      7         ) ProductNum
      8  FROM xmltablestore t
      9  ;
    
    PRODUCTNUM
    ----------
    6,3481E+10
    
    SQL> SELECT xmlcast(
      2          xmlquery('/Entries/Category/MapItem/@ProductNum'
      3           passing t.xml_column
      4           returning content
      5          )
      6          as varchar2(30)
      7         ) ProductNum
      8  FROM xmltablestore t
      9  ;
    
    PRODUCTNUM
    ------------------------------
    63481062975
    

    BTW, extract and extractvalue functions are deprecated in version 11.2.
    Oracle now recommends using XMLCast/XMLQuery.

  • XML file too large or too large XML element

    I try to import an xml file into the repository and have it shred in the object-relational tables. I signed up a diagram and it created types, triggers and object-relational xml_tables. The complete xml file is > 80 MB. XDB created all fields VARCHAR2 (4000).

    error code when you import the complete XML file. That's what I need to fix in the end.
    DECLARE
      res BOOLEAN;
    BEGIN
      res := DBMS_XDB.createResource('/home/pharma/drugbank.xml', 
                    bfilename('XMLPHARMA', 'drugbank.xml'),
                    nls_charset_id('AL32UTF8'));
    END;
    /
    COMMIT;
    
    XML file encounters errors on the import.
    An error was encountered performing the requested operation
    ORA-30951: Element or attribute at Xpath references exceeds maximum length
    ORA-06512 at "XDB.DBMS_XDB", line 315
    ORA-06512 at line 4
    30951.00000 - "Element or attribute at Xpath %x exceeds maximum length"
    *Cause: An attempt was made to insert a node of length exceeding the maximum length (specified by the maxLength facet) into an XML document.
    *Action: Do not attempt to add a node exceeding the maximum length to XML documents.
    Vendor code 30951Error at Line:18
    I guess that some fields have lengths > 4000 max. I intend to annotate the schema with SQLType = 'CLOB', but there are fields to change. I could copy the xml file and reduce this xml file to a record of any in the tables. My plan was to write a review on the bfile to get the lengths of some fields, annotate the .xsd with CLOB when needed and then import it again. To do this, I have a 1 imported in a table and as a bfile type recording file.

    Here is my code selection length in a generated object-relational table as a single folder.
    CREATE OR REPLACE VIEW pharma.drugs_vw AS
    SELECT d.*
    FROM drugs, XMLTABLE
      ('/drugs' PASSING OBJECT_VALUE COLUMNS
        drugbank_id        VARCHAR2(20)   PATH 'drug/drugbank-id',
        name               VARCHAR2(50)   PATH 'drug/name',
        description        VARCHAR2(4000) PATH 'drug/description'    
      ) d
    /
    
    select max(length(drugbank_id)) as dbidlen,
          max(length(name)) as nmlen,
          max(length(description)) as desclen
    from drugs_vw;
    
            DBIDLEN           NMLEN         DESCLEN
    --------------- --------------- ---------------
                  7               9             229
    
    1 row selected.
    Here's the code for the bfile. Same results, but using deprecated functions. I read the white paper, Oracle XML DB: best practices for optimal performance of queries XML. It is said that the function extract(), extractvalue(), Table (XMLSequence ()) and XMLType() are deprecated in 11 GR 2.
    -- Note extractvalue is deprecated in 11gr2 replaced by W3C standard
    --                                          XMLCast(XMLQuery())
    -- TABLE(XMLSequence) is replaced by XMLTable
    -- XMLType() is replaced by XMLParse()
    SELECT max(length(extractvalue(column_value, '/drug/drugbank-id'))) dbidlen,
           max(length(extractvalue(column_value, '/drug/name'))) nmlen,
           max(length(extractvalue(column_value, '/drug/description'))) desclen
    FROM TABLE(XMLSequence(XMLTYPE(bfilename('XMLPHARMA',
    'db00001.xml'),nls_charset_id('AL32UTF8')).extract('/drugs/drug'))) d
    WHERE ROWNUM <= 5;
    
            DBIDLEN           NMLEN         DESCLEN
    --------------- --------------- ---------------
                  7               9             229
    Is this better code to get the maximum length of a bfile type xml fields? Here's what I have so far. It works on a simple drugbank id.
    SELECT max(length(drugbank_id)) AS dbidlen,
           max(length(name)) AS nmlen,
           max(length(description)) AS desclen
    FROM (XMLTABLE('*'
                    PASSING (XMLType(bfilename('XMLPHARMA', 'db00001.xml'),nls_charset_id('AL32UTF8')))
                    COLUMNS
        drugbank_id        VARCHAR2(20)   PATH 'drug/drugbank-id',
        name               VARCHAR2(50)   PATH 'drug/name',
        description        VARCHAR2(4000) PATH 'drug/description'
      )
    );
    I try to run it on the full file and get this error
    Error report:
    SQL Error: ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00007: unexpected end-of-file encountered
    31011. 00000 -  "XML parsing failed"
    *Cause:    XML parser returned an error while trying to parse the document.
    *Action:   Check if the document to be parsed is valid.
    The code to create patterns and object-relational tables. It worked well.
    set serveroutput on
    -- Create resource file for schema
    DECLARE
      res BOOLEAN;
    BEGIN
      res := DBMS_XDB.createResource('/home/pharma/drugbank.xsd', 
                    bfilename('XMLPHARMA', 'drugbank.xsd'),
                    nls_charset_id('AL32UTF8'));
      COMMIT;
    END;
    /
    
    -- optional debugging of create types and tables if you want a trace
    ALTER SESSION SET EVENTS = '31098 TRACE NAME CONTEXT FOREVER';
    
    BEGIN
      DBMS_XMLSCHEMA.registerSchema(
          SCHEMAURL => 'http://localhost:8080/home/pharma/drugbank.xsd',
          SCHEMADOC => bfilename('XMLPHARMA', 'drugbank.xsd'),
          CSID      => nls_charset_id('AL32UTF8'),
          LOCAL     => TRUE,
          GENTYPES  => TRUE,
          GENTABLES => TRUE,
          OWNER     => 'PHARMA');
      COMMIT;
    END;
    /
    SQL> select * from v$version;
    BANNER
    ---------------------------------------------------------------
    Oracle Database 11g 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 32-bit Windows: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    Follows the xml schema. Sorry for the length, but I think I might break something if I he snipped.
    <?xml version="1.0" encoding="UTF-8"?>
         <xs:schema  
         xmlns:xs="http://www.w3.org/2001/XMLSchema"  
         xmlns:xdb="http://xmlns.oracle.com/xdb"
         >
    
         <!-- General type definitions -->
         <xs:simpleType name="DecimalOrEmptyType">
              <xs:union memberTypes="xs:decimal EmptyStringType"/>
         </xs:simpleType>
         <xs:simpleType name="EmptyStringType">
              <xs:restriction base="xs:string">
                   <xs:enumeration value=""/>
              </xs:restriction>
         </xs:simpleType>
    
         <!-- Element Definitions -->
         <!-- Drug secondary accession number definition begins -->
         <xs:element name="secondary-accession-numbers" xdb:defaultTable="SECONDARY_ACCESSION_NUMBERS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="secondary-accession-number" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug secondary accession number definition ends -->
         <!-- Drug groups definition begins -->
         <xs:element name="groups" xdb:defaultTable="GROUPS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="group">
                             <xs:simpleType>
                                  <xs:restriction base="xs:string">
                                       <xs:enumeration value="approved"/>
                                       <xs:enumeration value="illicit"/>
                                       <xs:enumeration value="experimental"/>
                                       <xs:enumeration value="withdrawn"/>
                                       <xs:enumeration value="nutraceutical"/>
                                  </xs:restriction>
                             </xs:simpleType>
                        </xs:element>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug groups definition ends -->
         <!-- Drug taxonomy definition begins -->
         <xs:element name="substructure">
              <xs:complexType>
                   <xs:simpleContent>
                        <xs:extension base="xs:string">
                             <xs:attribute name="class" type="xs:string" use="required"/>
                        </xs:extension>
                   </xs:simpleContent>
              </xs:complexType>
         </xs:element>
         <xs:element name="substructures" xdb:defaultTable="SUBSTRUCTURES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="substructure"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="taxonomy" xdb:defaultTable="TAXONOMY">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="kingdom" type="xs:string"/>
                        <xs:element ref="substructures"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug taxonomy definition ends -->
         <!-- Drug brands definition begins -->
         <xs:element name="brands" xdb:defaultTable="BRANDS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="brand" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug brands definition ends -->
         <!-- Drug mixtures definition begins -->
         <xs:element name="mixture">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="name" type="xs:string"/>
                        <xs:element name="ingredients" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="mixtures" xdb:defaultTable="MIXTURES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="mixture"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug mixtures definition ends -->
         <!-- Drug packagers definition begins -->
         <xs:element name="packager">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="name" type="xs:string"/>
                        <xs:element name="url" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="packagers" xdb:defaultTable="PACKAGERS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="packager"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug packagers definition ends -->
         <!-- Drug manufacturers definition begins -->
         <xs:element name="manufacturer">
              <xs:complexType>
                   <xs:simpleContent>
                        <xs:extension base="xs:string">
                             <xs:attribute name="generic" type="xs:string" use="required"/>
                        </xs:extension>
                   </xs:simpleContent>
              </xs:complexType>
         </xs:element>
         <xs:element name="manufacturers" xdb:defaultTable="MANUFACTURERS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="manufacturer"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug manufactures definition ends -->
         <!-- Drug pricing definition begins -->
         <xs:element name="cost">
              <xs:complexType>
                   <xs:simpleContent>
                        <xs:extension base="xs:string">
                             <xs:attribute name="currency" type="xs:string" use="required"/>
                        </xs:extension>
                   </xs:simpleContent>
              </xs:complexType>
         </xs:element>
         <xs:element name="price">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="description" type="xs:string"/>
                        <xs:element ref="cost"/>
                        <xs:element name="unit" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="prices" xdb:defaultTable="PRICES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="price"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug pricing definition ends -->
         <!-- Drug categories definition begins -->
         <xs:element name="categories" xdb:defaultTable="CATEGORIES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="category" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug categories definition ends -->
         <!-- Drug affected orgainsms definition begins -->
         <xs:element name="affected-organisms" xdb:defaultTable="AFFECTED_ORGANISMS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="affected-organism" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug affected organisms definition ends -->
         <!-- Drug dosage definition begins -->
         <xs:element name="dosage">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="form" type="xs:string"/>
                        <xs:element name="route" type="xs:string"/>
                        <xs:element name="strength" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="dosages" xdb:defaultTable="DOSAGES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="dosage"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug dosages definition ends -->
         <!-- Drug ATC codes definition begins -->
         <xs:element name="atc-codes" xdb:defaultTable="ATC_CODES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="atc-code" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug ATC codes definition ends -->
         <!-- Drug AHFS codes definition begins -->
         <xs:element name="ahfs-codes" xdb:defaultTable="AHFS_CODES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="ahfs-code" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug AHFS codes definition ends -->
         <!-- Drug Patent definition begins -->
         <xs:element name="patent">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="number" type="xs:string"/>
                        <xs:element name="country" type="xs:string"/>
                        <xs:element name="approved" type="xs:string"/>
                        <xs:element name="expires" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="patents" xdb:defaultTable="PATENTS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="patent"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug patent definition ends -->
         <!-- Drug food interactions definition begins -->
         <xs:element name="food-interactions" xdb:defaultTable="FOOD_INTERACTIONS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="food-interaction" type="xs:string" maxOccurs="unbounded" minOccurs="0"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug food interactions definition ends -->
         <!-- Drug drug interactions definition begins -->
         <xs:element name="drug-interaction">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="drug" type="xs:integer"/>
                        <xs:element name="description" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="drug-interactions" xdb:defaultTable="DRUG_INTERACTIONS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="drug-interaction"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug drug interactions definition ends -->
         <!-- Drug protein sequences (biotech) definition begins -->
         <xs:element name="protein-sequences" xdb:defaultTable="PROTEIN_SEQUENCES">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element name="protein-sequence" type="SequenceType"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug protein sequences (biotech) definition ends-->
         <!-- Drug external links definition begins -->
         <xs:element name="external-link">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="resource" type="xs:string"/>
                        <xs:element name="url" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="external-links" xdb:defaultTable="EXTERNAL_LINKS">
              <xs:complexType>
                   <xs:sequence maxOccurs="unbounded" minOccurs="0">
                        <xs:element ref="external-link"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug external links definition ends -->
         <!-- Drug targets definition begins -->
         <xs:element name="targets" xdb:defaultTable="TARGETS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="target" type="TargetBondType" minOccurs="0" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug targets definition ends -->
         <!-- Drug enzymes definition begins -->
         <xs:element name="enzymes" xdb:defaultTable="ENZYMES">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="enzyme" type="BondType" minOccurs="0" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug enzmes definition ends -->
         <!-- Drug transporters definition begins -->
         <xs:element name="transporters" xdb:defaultTable="TRANSPORTERS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="transporter" type="BondType" minOccurs="0" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug transporters definition ends -->
         <!-- Drug carriers definition begins -->
         <xs:element name="carriers" xdb:defaultTable="CARRIERS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="carrier" type="BondType" minOccurs="0" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Drug carriers definition ends -->
         <!-- Partner  Pfams definition begins -->
         <xs:element name="pfam">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="identifier" type="xs:string"/>
                        <xs:element name="name" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="pfams" xdb:defaultTable="PFAMS">
              <xs:complexType>
                   <xs:sequence minOccurs="0" maxOccurs="unbounded">
                        <xs:element ref="pfam"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Partner  Pfams definition end -->
         <!-- Partner  GO Classification definition begins -->
         <xs:element name="go-classifier">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="category" type="xs:string"/>
                        <xs:element name="description" type="xs:string"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:element name="go-classifiers" xdb:defaultTable="GO_CLASSIFIERS">
              <xs:complexType>
                   <xs:sequence minOccurs="0" maxOccurs="unbounded">
                        <xs:element ref="go-classifier"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <!-- Partner  GO Classification definition ends -->
         <!-- Partner Essentiality definition begins -->
         <xs:element name="essentiality">
              <xs:simpleType>
                   <xs:restriction base="xs:string">
                        <xs:enumeration value="Essential"/>
                        <xs:enumeration value="Non-Essential"/>
                   </xs:restriction>
              </xs:simpleType>
         </xs:element>
         <!-- Partner Essentiality definition ends -->
         
         <!-- Complex Type Definitions -->
         <xs:complexType name="SequenceType">
              <xs:sequence>
                   <xs:element name="header" type="xs:string"/>
                   <xs:element name="chain" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="PropertyType">
              <xs:sequence>
                   <xs:element name="kind">
                        <xs:simpleType>
                             <xs:restriction base="xs:string">
                                  <xs:enumeration value="logP"/>
                                  <xs:enumeration value="logS"/>
                                  <xs:enumeration value="logP/hydrophobicity"/>
                                  <xs:enumeration value="Water Solubility"/>
                                  <xs:enumeration value="caco2 Permeability"/>
                                  <xs:enumeration value="pKa"/>
                                  <xs:enumeration value="IUPAC Name"/>
                                  <xs:enumeration value="Molecular Weight"/>
                                  <xs:enumeration value="Monoisotopic Weight"/>
                                  <xs:enumeration value="SMILES"/>
                                  <xs:enumeration value="Molecular Formula"/>
                                  <xs:enumeration value="InChI"/>
                                  <xs:enumeration value="InChIKey"/>
                             </xs:restriction>
                        </xs:simpleType>
                   </xs:element>
                   <xs:element name="value" type="xs:string"/>
                   <xs:element name="source">
                        <xs:simpleType>
                             <xs:restriction base="xs:string">
                                  <xs:enumeration value="JChem"/>
                                  <xs:enumeration value="ALOGPS"/>
                                  <xs:enumeration value=""/>
                             </xs:restriction>
                        </xs:simpleType>
                   </xs:element>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="PropertiesType">
              <xs:sequence>
                   <xs:element name="property" type="PropertyType" minOccurs="0" maxOccurs="unbounded"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="SynonymsType">
              <xs:sequence maxOccurs="unbounded" minOccurs="0">
                   <xs:element name="synonym" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="IdentifiersType">
              <xs:sequence maxOccurs="unbounded" minOccurs="0">
                   <xs:element name="external-identifier">
                        <xs:complexType>
                             <xs:sequence>
                                  <xs:element name="resource" type="xs:string"/>
                                  <xs:element name="identifier" type="xs:string"/>
                             </xs:sequence>
                        </xs:complexType>
                   </xs:element>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="BondActionsType">
              <xs:sequence maxOccurs="unbounded" minOccurs="0">
                   <xs:element name="action" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="BondType">
              <xs:sequence>
                   <xs:element name="actions" type="BondActionsType"/>
                   <xs:element name="references" type="xs:string"/>
              </xs:sequence>
              <xs:attribute name="position" type="xs:integer" use="optional"/>
              <xs:attribute name="partner" type="xs:integer"/>
         </xs:complexType>
         <xs:complexType name="TargetBondType">
              <xs:complexContent>
                   <xs:extension base="BondType">
                        <xs:sequence>
                             <xs:element name="known-action">
                                  <xs:simpleType>
                                       <xs:restriction base="xs:string">
                                            <xs:enumeration value="yes"/>
                                            <xs:enumeration value="no"/>
                                            <xs:enumeration value="unknown"/>
                                       </xs:restriction>
                                  </xs:simpleType>
                             </xs:element>
                        </xs:sequence>
                   </xs:extension>
              </xs:complexContent>
         </xs:complexType>
         
         <xs:complexType name="PartnerType">
              <xs:sequence>
                   <xs:element name="name" type="xs:string"/>
                   <xs:element name="general-function" type="xs:string"/>
                   <xs:element name="specific-function" type="xs:string"/>
                   <xs:element name="gene-name" type="xs:string"/>
                   <xs:element name="locus" type="xs:string"/>
                   <xs:element name="reaction" type="xs:string"/>
                   <xs:element name="signals" type="xs:string"/>
                   <xs:element name="cellular-location" type="xs:string"/>
                   <xs:element name="transmembrane-regions" type="xs:string"/>
                   <xs:element name="theoretical-pi" type="DecimalOrEmptyType"/>
                   <xs:element name="molecular-weight" type="DecimalOrEmptyType"/>
                   <xs:element name="chromosome" type="xs:string"/>
                   <xs:element ref="essentiality"/>
                   <xs:element name="references" type="xs:string"/>
                   <xs:element name="external-identifiers" type="IdentifiersType"/>
                   <xs:element name="synonyms" type="SynonymsType"/>
                   <xs:element name="protein-sequence" type="SequenceType" minOccurs="0"/>
                   <xs:element name="gene-sequence" type="SequenceType" minOccurs="0"/>
                   <xs:element ref="pfams"/>
                   <xs:element ref="go-classifiers"/>
              </xs:sequence>
              <xs:attribute name="id" type="xs:integer" use="required"/>
         </xs:complexType>
         <xs:complexType name="DrugType">
              <xs:sequence>
                   <xs:element name="drugbank-id" type="xs:string"/>
                   <xs:element name="name" type="xs:string"/>
                   <xs:element name="description" type="xs:string"/>
                   <xs:element name="cas-number" type="xs:string"/>
                   <xs:element name="general-references" type="xs:string"/>
                   <xs:element name="synthesis-reference" type="xs:string"/>
                   <xs:element name="indication" type="xs:string"/>
                   <xs:element name="pharmacology" type="xs:string"/>
                   <xs:element name="mechanism-of-action" type="xs:string"/>
                   <xs:element name="toxicity" type="xs:string"/>
                   <xs:element name="biotransformation" type="xs:string"/>
                   <xs:element name="absorption" type="xs:string"/>
                   <xs:element name="half-life" type="xs:string"/>
                   <xs:element name="protein-binding" type="xs:string"/>
                   <xs:element name="route-of-elimination" type="xs:string"/>
                   <xs:element name="volume-of-distribution" type="xs:string"/>
                   <xs:element name="clearance" type="xs:string"/>
                   <xs:element ref="secondary-accession-numbers"/>
                   <xs:element ref="groups"/>
                   <xs:element ref="taxonomy"/>
                   <xs:element name="synonyms" type="SynonymsType"/>
                   <xs:element ref="brands"/>
                   <xs:element ref="mixtures"/>
                   <xs:element ref="packagers"/>
                   <xs:element ref="manufacturers"/>
                   <xs:element ref="prices"/>
                   <xs:element ref="categories"/>
                   <xs:element ref="affected-organisms"/>
                   <xs:element ref="dosages"/>
                   <xs:element ref="atc-codes"/>
                   <xs:element ref="ahfs-codes"/>
                   <xs:element ref="patents"/>
                   <xs:element ref="food-interactions"/>
                   <xs:element ref="drug-interactions"/>
                   <xs:element ref="protein-sequences" minOccurs="0"/><!-- Only present for biotech drugs -->
                   <xs:element name="calculated-properties" type="PropertiesType" minOccurs="0"/><!-- Only present for small molecule drugs -->
                   <xs:element name="experimental-properties" type="PropertiesType"/>
                   <xs:element name="external-identifiers" type="IdentifiersType"/>
                   <xs:element ref="external-links"/>
                   <xs:element ref="targets"/>
                   <xs:element ref="enzymes"/>
                   <xs:element ref="transporters"/>
                   <xs:element ref="carriers"/>
              </xs:sequence>
              <xs:attribute name="type" use="required">
                   <xs:simpleType>
                        <xs:restriction base="xs:string">
                             <xs:enumeration value="small molecule"/>
                             <xs:enumeration value="biotech"/>
                        </xs:restriction>
                   </xs:simpleType>
              </xs:attribute>
              <xs:attribute name="updated" type="xs:string" use="required"/>
              <xs:attribute name="created" type="xs:string" use="required"/>
              <xs:attribute name="version" type="xs:decimal" use="required"/>
         </xs:complexType>
         
         <xs:element name="drugs"  xdb:defaultTable="DRUGS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="drug" type="DrugType" minOccurs="0" maxOccurs="unbounded" />
                        <xs:element name="partners">
                             <xs:complexType>
                                  <xs:sequence>
                                       <xs:element name="partner" type="PartnerType" minOccurs="0" maxOccurs="unbounded" />
                                  </xs:sequence>
                             </xs:complexType>
                        </xs:element>
                   </xs:sequence>
              </xs:complexType>
         
              <xs:keyref name="targetPartnerIdKeyRef" refer="partnerIdKey">
                   <xs:selector xpath="drug/targets/*"/>
                   <xs:field xpath="@partner"/>
              </xs:keyref>
              <xs:keyref name="enzymePartnerIdKeyRef" refer="partnerIdKey">
                   <xs:selector xpath="drug/enzymes/*"/>
                   <xs:field xpath="@partner"/>
              </xs:keyref>
              <xs:keyref name="transporterPartnerIdKeyRef" refer="partnerIdKey">
                   <xs:selector xpath="drug/transporters/*"/>
                   <xs:field xpath="@partner"/>
              </xs:keyref>
              <xs:keyref name="carrierPartnerIdKeyRef" refer="partnerIdKey">
                   <xs:selector xpath="drug/carriers/*"/>
                   <xs:field xpath="@partner"/>
              </xs:keyref>
              <xs:key name="partnerIdKey">
                   <xs:selector xpath=".//partner"/>
                   <xs:field xpath="@id"/>
              </xs:key>
         </xs:element>     
    </xs:schema>
    Optimization white paper request
    http://www.Oracle.com/technetwork/database/features/xmldb/xmlqueryoptimize11gr2-168036.PDF

    Well Yes... You need not put GENTABLES-online TRUE when recording object relational. There are no structures in XML schema that require tables on online storage...

    SQL> DECLARE
      2    V_XMLSCHEMA XMLTYPE := xmltype(bfilename('&USERNAME', 'drugbank.xsd'),nls_charset_id('AL32UTF8'));
      3  BEGIN
      4          DBMS_XMLSCHEMA_ANNOTATE.disableDefaultTableCreation(V_XMLSCHEMA);
      5          DBMS_XMLSCHEMA_ANNOTATE.disableMaintainDOM(V_XMLSCHEMA);
      6          DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'BondType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'references','CLOB',TRUE);
      7          DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'PartnerType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'references','CLOB',TRUE);
      8          DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'DrugType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'general-references','CLOB',TRUE);
      9          DBMS_XMLSCHEMA_ANNOTATE.setSQLType(V_XMLSCHEMA,DBMS_XDB_CONSTANTS.XSD_COMPLEX_TYPE,'SequenceType',DBMS_XDB_CONSTANTS.XSD_ELEMENT,'chain','CLOB',TRUE);
     10    DBMS_XMLSCHEMA.registerSchema(
     11        SCHEMAURL => :SCHEMAURL,
     12        SCHEMADOC => V_XMLSCHEMA,
     13        LOCAL     => TRUE,
     14        GENTYPES  => TRUE,
     15        GENTABLES => TRUE);
     16  END;
     17  /
    old   2:   V_XMLSCHEMA XMLTYPE := xmltype(bfilename('&USERNAME', 'drugbank.xsd'),nls_charset_id('AL32UTF8'));
    new   2:   V_XMLSCHEMA XMLTYPE := xmltype(bfilename('PHARMA', 'drugbank.xsd'),nls_charset_id('AL32UTF8'));
    
    PL/SQL procedure successfully completed.
    
    Elapsed: 00:00:01.65
    SQL> CREATE TABLE drugs_xmltype OF XMLTYPE
      2  XMLSCHEMA "http://lims.drugbank.ca/docs/drugbank.xsd"
      3  ELEMENT "drugs"
      4  /
    
    Table created.
    

    results in

    SQL*Plus: Release 11.2.0.3.0 Production on Fri Apr 29 16:14:00 2011
    
    Copyright (c) 1982, 2011, Oracle.  All rights reserved.
    
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    
    SQL> select table_name from user_xml_tables;
    
    TABLE_NAME
    ------------------------------
    DRUGS_XMLTYPE
    
    SQL> select count(*) from user_nested_tables;
    
      COUNT(*)
    ----------
            36
    
    SQL>
    
  • XMLTYPE excerpt

    Hello

    <? XML version = "1.0" encoding = "utf-8"? >
    < soap envelope: xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" container = "http://www.w3.org/2001/XMLSchema" xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/" >
    < soap: Body >
    < HelloWorldResponse xmlns = "http://tempuri.org/" >
    Oracle of < HelloWorldResult > < / HelloWorldResult >
    < / HelloWorldResponse >
    < / soap: Body >
    < / envelope soap: >


    Please how could extract the word "oracle" of HelloWorldResult tag?

    Thanks in advance

    Hello

    You can use the extractValue() function.
    Or, if you are using the version 11g, Oracle recommends to use XMLQuery() instead:

    DECLARE
    
     xmldoc xmltype := xmltype(
    '
    
    
    
    Oracle
    
    
    ');
    
     res varchar2(30);
    
    BEGIN
    
     -- version <= 10.2
     select extractvalue( xmldoc
                        , '/soap:Envelope/soap:Body/ns0:HelloWorldResponse/ns0:HelloWorldResult'
                        , 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", xmlns:ns0="http://tempuri.org/"' )
     into res
     from dual;
    
     dbms_output.put_line(res);
    
     -- version >= 11.1
     select xmlcast(
              xmlquery(
               'declare namespace soap="http://schemas.xmlsoap.org/soap/envelope/"; (::)
                declare namespace ns0="http://tempuri.org/"; (::)
                /soap:Envelope/soap:Body/ns0:HelloWorldResponse/ns0:HelloWorldResult'
               passing xmldoc
               returning content
              )
              as varchar2(30)
            )
     into res
     from dual;
    
     dbms_output.put_line(res);
    
    END;
    /
    
  • problems with selection of XMLType column value

    I want to extract my XMLType column values. Can someone tell me why this works
    select XMLCAST
              (
                XMLQUERY
                (
                   'declare default element namespace  "urn:hl7-org:v3"; (: :)
                    declare namespace voc = "urn:hl7-org:v3/voc"; (: :)
                    $doc/ClinicalDocument/recordTarget/patientRole/patient/name/family'
                    passing CCD_DOC as "doc"
                    returning content
                )
                as VARCHAR2(4000)
              )
         from CCD
    but it does not work?
    select
        ccdid,
        extractvalue(CCD_DOC,'/recordTarget/patientRole/patient/name/given') "given",
        extractvalue(CCD_DOC,'/recordTarget/patientRole/patient/name/family') "family",
        extractvalue(CCD_DOC,'/recordTarget/patientRole/providerOranization/name') "name",
        extractvalue(CCD_DOC, 'title') as Title
    from CCD
    where ClinicalDocument is the root element?

    I don't get any errors on the other, but the three XML derived columns are null. The values are not retrieved while the values ARE retrieved using the first method.

    Thank you!

    XMLTable...

    select x.*
      from CCD,
           XMLTable
           (
             xmlNamespaces
             (
               default 'urn:hl7-org:v3',
               'urn:hl7-org:v3/voc' as "voc"
             ),
             '$doc/ClinicalDocument/recordTarget/patientRole'
             passing CCD_DOD as "doc"
             columns
             given varchar2(128) path 'patient/name/given',
             family varchar2(128) path 'patient/name/family',
             name varchar2(128) path 'providerOranization/name'
           ) x
    
  • XMLType column selection

    I have the following in an XMLType column:

    "< ClinicalDocument xmlns =" "urn: hl7 - org:v3" xmlns:voc = "urn: hl7 - org:v3 / VOC" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" >
    < root typeId = "2.16.840.1.113883.1.3" extension = "POCD_HD000040" / >
    < root templateId = "2.16.840.1.113883.10.20.1" / >
    < root id = "2.16.840.1.113883.3.140.1.0.6.1" extension = "7380300531250060" / >
    < code = "34133-9" displayName = "summary of the note of the episode" codeSystem = "2.16.840.1.113883.6.1" / >
    < title > Madison Medical Center P. A. continuity of care Document < /title >
    < value effectiveTime = "20090508115140-0400" / >
    < confidentialityCode code = "N" displayName = "Normal" codeSystem = "2.16.840.1.113883.5.25" / >
    < code CodeLangue = "en-US" / >
    < recordTarget >
    < patientRole >
    < root id = "2.16.840.1.113883.3.140.1.0.6.4" extension = "10" / >
    < root id = "2.16.840.1.113883.4.1" extension = "345003434" / >
    < addr >
    < streetAddressLine > 3456 West Palm < / streetAddressLine >
    apt #34 < streetAddressLine > < / streetAddressLine >
    < City > Madison < / City >
    CA < State > < / State >
    < code postal > 95653 < / code >
    < / addr >
    < telecom use = "HP" value = "such: (916) 555-3293" / > "
    < value telecom = "mailto:[email protected]" / >
    < patient >
    < name >
    < given > name < / view >
    < given > W < / view >
    < family > LastName < / family >
    < / name >
    < administrativeGenderCode code = "M" codeSystem = "2.16.840.1.113883.5.1" codeSystemName = "AdministrativeGender" / >
    < birth value = "19380816" / >
    < maritalStatusCode code = "M" displayName = "Mary" codeSystem = "2.16.840.1.113883.11.12212" codeSystemName = "MaritalStatus" / >
    < code raceCode = "2106-3" displayName = "White" codeSystem = "2.16.840.1.113883.11.14914" codeSystemName = 'Race' / >
    < / patient >
    < / ClinicalDocument >

    When I run some extractvalue (' CCD_DOC, ' recordTarget/patientRole/patient/name/family ") of the CCD; no error is returned, but also, I don't get the value. What Miss me?

    In a Word - namespace definitions...

    Here is an example written using XMLQuery, rather than extractValue, which is the preferred approach in 10.2.x and later...

    SQL> with CCD as
      2  (
      3  select XMLTYPE(
      4  '
      5     
      6     
      7     
      8     
      9     Madison Medical Center P. A. Continuity of Care Document
     10     
     11     
     12     
     13     
     14             
     15                     
     16                     
     17                     
     18                             3456 West Palm
     19                             Apt. #34
     20                             Madison
     21                             CA
     22                             95653
     23                     
     24                     
     25                     
     26                     
     27                             
     28                                     FirstName
     29                                     W
     30                                     LastName
     31                             
     32                             
     33                             
     34                             
     35                             
     36                     
     37             
     38     
     39  ') as CCD_DOC from dual
     40  )
     41  select XMLCAST
     42         (
     43           XMLQUERY
     44           (
     45              'declare default element namespace  "urn:hl7-org:v3"; (: :)
     46               declare namespace voc = "urn:hl7-org:v3/voc"; (: :)
     47               $doc/ClinicalDocument/recordTarget/patientRole/patient/name/family'
     48               passing CCD_DOC as "doc"
     49               returning content
     50           )
     51           as VARCHAR2(4000)
     52         )
     53    from CCD
     54  /
    
    XMLCAST(XMLQUERY('DECLAREDEFAULTELEMENTNAMESPACE"URN:HL7-ORG:V3";(::)DECLARENAME
    --------------------------------------------------------------------------------
    LastName
    
    SQL>
    
  • XmlIndex subsetting question


    I have a table EMP that contains an xmltype column called empinfo

    CREATE TABLE EMP
    (
    DATE EVENT_DATE,
    empinfo SYS. XMLTYPE
    )
    XMLTYPE XML STORE AS BINARY XML NAVIGATION

    This pass of xmltype contains xml unstructured documents. I am interested in indexing on 'empno '.
    I am able to create an index, but it will be only works on the first level.


    CREATE INDEX subset_xmlindex ON emp (empinfo)
    indexType IS xdb.xmlindex
    parameters ("PATHS (INCLUDE (//empno))
    path table subset_pathtable (undesirable tablespace)');

    When I do the next xmlexists, he found all the empno, but it does not use the index.

    XMLExists ('/ / * [empno = 171943270] ' from empinfo)

    When I do that it finds the empno in the fitrst level and use the index. but it does not find the empno < empinfo > level.
    and xmlexists ('/ person / * [empno = 1073630546]' from empinfo)


    question: How can I use the index on all the elements 'empno' wherever they are in the doc.
    is it still possible? the table contains millions of records.

    doc suggest using //empno in the index include the will of the index on the regradless of all the empno hence they are.

    -xml1

    < person >
    < personrecord >
    < name >
    .....
    < empno >
    ...
    < / personrecord >
    < / person >


    -xml2
    < person >
    < personinfo >
    < name >
    ....
    < empinfo >
    < empno >
    ....
    < / empinfo >
    ....
    < / personrecord >
    < / person >

    Version database please?

    And question: is there still a single node "empno" by the document?

    The following works for me.

    Make sure you pass the link as string variable, no number (unless you create an additional digital index on the VALUE of path):

    SQL> select *
      2  from emp
      3  where xmlexists('//empno[.=$empno]'
      4          passing empinfo
      5                , '7777' as "empno"
      6        )
      7  ;
    
    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 1962240707
    
    -------------------------------------------------------------------------------------------------------------------
    | Id  | Operation                        | Name                           | Rows  | Bytes | Cost (%CPU)| Time     |
    -------------------------------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT                 |                                |     1 |   145 |     5  (20)| 00:00:01 |
    |   1 |  NESTED LOOPS                    |                                |     1 |   145 |     5  (20)| 00:00:01 |
    |   2 |   VIEW                           | VW_SQ_1                        |     1 |    12 |     3   (0)| 00:00:01 |
    |   3 |    HASH UNIQUE                   |                                |     1 |    47 |            |          |
    |   4 |     NESTED LOOPS                 |                                |       |       |            |          |
    |   5 |      NESTED LOOPS                |                                |     1 |    47 |     3   (0)| 00:00:01 |
    |   6 |       TABLE ACCESS BY INDEX ROWID| X$PT72R2I5S5V9A9VE0GOACG0GKWIG |     1 |    12 |     2   (0)| 00:00:01 |
    |*  7 |        INDEX RANGE SCAN          | X$PR72R2I5S5V9A9VE0GOACG0GKWIG |     1 |       |     1   (0)| 00:00:01 |
    |*  8 |       INDEX RANGE SCAN           | SYS166546_SUBSET_XM_VALUE_IX   |     7 |       |     0   (0)| 00:00:01 |
    |*  9 |      TABLE ACCESS BY INDEX ROWID | SYS166546_SUBSET_XM_PATH_TABLE |     1 |    35 |     1   (0)| 00:00:01 |
    |  10 |   TABLE ACCESS BY USER ROWID     | EMP                            |     1 |   133 |     1   (0)| 00:00:01 |
    -------------------------------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       7 - access(SYS_PATH_REVERSE("PATH")>=HEXTORAW('021FD8')  AND
                  SYS_PATH_REVERSE("PATH")
    

    Alternatively, if each doc contains at most one occurrence of 'empno', you can add a virtual column that retrieves and create an index on this column:

    SQL> alter table emp add empno number generated always as (
      2    xmlcast(xmlquery('//empno' passing empinfo returning content) as number)
      3  )
      4  virtual ;
    
    Table altered.
    
    SQL>
    SQL> create index emp_empno_i on emp (empno);
    
    Index created.
    
    SQL> select * from emp where empno = 7777;
    
    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 1114809652
    
    -------------------------------------------------------------------------------------------
    | Id  | Operation                   | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    -------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT            |             |     1 |   133 |     2   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| EMP         |     1 |   133 |     2   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | EMP_EMPNO_I |     1 |       |     1   (0)| 00:00:01 |
    -------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       2 - access("EMPNO"=7777)
    
  • Fill a Table using XML?

    Hello

    Can read XML and the insertion/upgrade to update / delete any table?

    Assumes that the XML is stored in a column

    Is there something similar loan?


    With the help of:

    Oracle Database 11 g Enterprise Edition Release 11.2.0.4.0 - 64 bit Production
    PL/SQL Release 11.2.0.4.0 - Production
    CORE Production 11.2.0.4.0
    AMT for Linux: Version 11.2.0.4.0 - Production
    NLSRTL Version 11.2.0.4.0 - Production







    A few ideas, using DBMS_XMLSTORE:

    SQL> create table table2 (code varchar2(30) primary key, dt_ini date, aliq_pis number);
    
    Table created.
    
    SQL>
    SQL> create or replace procedure merge_record (p_rec in xmltype)
      2  is
      3
      4    cursor c_tab_cols (p_table_name in varchar2)
      5    is
      6      with pk_cols (column_name) as (
      7        select column_name
      8        from user_cons_columns
      9        where constraint_name = (
     10          select constraint_name
     11          from user_constraints
     12          where table_name = p_table_name
     13          and constraint_type = 'P'
     14        )
     15      )
     16      select tc.column_name
     17           , nvl2(cc.column_name, 'Y', 'N') as is_pk
     18      from user_tab_cols tc
     19           left outer join pk_cols cc on cc.column_name = tc.column_name
     20      where tc.table_name = p_table_name
     21      and tc.virtual_column = 'NO' ;
     22
     23    tab_name  user_tables.table_name%type;
     24    ctx       dbms_xmlstore.ctxHandle;
     25    numrows   number;
     26
     27  begin
     28
     29    -- get embedded table name
     30    select xmlcast(xmlquery('/TABLE/@tableName' passing p_rec returning content) as varchar2(30))
     31    into tab_name
     32    from dual;
     33
     34    -- set target table
     35    ctx := dbms_xmlstore.newContext(tab_name);
     36    -- and row tag name
     37    dbms_xmlstore.setRowTag(ctx, 'TABLE');
     38
     39    -- set columns to update
     40    for r in c_tab_cols (tab_name) loop
     41      dbms_xmlstore.setUpdateColumn(ctx, r.column_name);
     42      if r.is_pk = 'Y' then
     43        dbms_xmlstore.setKeyColumn(ctx, r.column_name);
     44      end if;
     45    end loop;
     46
     47    -- set date format
     48    execute immediate 'alter session set nls_date_format = "YYYY-MM-DD"';
     49
     50    -- update
     51    numrows := dbms_xmlstore.updateXML(ctx, p_rec);
     52
     53    -- if no row updated, try insert
     54    if numrows = 0 then
     55      dbms_xmlstore.clearKeyColumnList(ctx);
     56      numrows := dbms_xmlstore.insertXML(ctx, p_rec);
     57    end if;
     58
     59    dbms_xmlstore.closeContext(ctx);
     60
     61  end;
     62  /
    
    Procedure created.
    
    SQL>
    SQL>
    SQL> exec merge_record(xmltype('2009.70.012007-01-013
    ')) PL/SQL procedure successfully completed. SQL> select * from table2; CODE DT_INI ALIQ_PIS ------------------------------ ----------- ---------- 2009.70.01 01/01/2007 3 SQL> exec merge_record(xmltype('2009.70.012007-01-011
    ')) PL/SQL procedure successfully completed. SQL> exec merge_record(xmltype('2009.70.022007-01-011
    ')) PL/SQL procedure successfully completed. SQL> select * from table2; CODE DT_INI ALIQ_PIS ------------------------------ ----------- ---------- 2009.70.01 01/01/2007 1 2009.70.02 01/01/2007 1
  • Need advice on how to analyze the integrated calculation

    Hello

    I have a following problem:

    I have a table1 where I have the list of parameters to their current values;

    I have a table2 where I have a list of calculations that use these input parameters; the formula is stored as a string in a field

    I also have a table 3 where I have a list of calculations with the corresponding parameters, which are used by them;

    I also have 4 table, which must contain the result of a calculation according to the formula of table2 with values of parameters from table1

    requirement: procedure that will populate the table 4.

    my original idea was to do the following:

    1 call the procedure with the id of calculation

    2 extract the list of parameters for calculating id

    3 assign the values from table1 to the parameters of the step 2

    4. run the formula with the assigned values-> new procedure called with the formula and table of variables/parameters? dynamic SQL?

    can you please advise me what will be the best approach here?

    Thank you for the advice

    Some examples of data

    / * remove the table TEST_PARAMS;

    drop table TEST_CALC;

    drop table TEST_CALC_PARAM; * /

    /

    create the table TEST_PARAMS

    (

    param_id varchar2 (10),

    varchar2 value (50)

    )

    /

    insert into TEST_PARAMS values('param1',15);

    insert into TEST_PARAMS values('param2',25);

    /

    create the table TEST_CALC

    (

    CALC_ID varchar2 (10),

    CALC_FORMULA varchar2 (50)

    )

    /

    insert into TEST_CALC

    values ("CALC1",'(param1 + param2) / (param1 * param2)')

    /

    create the table TEST_CALC_PARAM

    (

    CALC_ID varchar2 (10),

    CALC_PARAM VARCHAR2 (10)

    )

    /

    insert into TEST_CALC_PARAM values ("CALC1", "param1");

    insert into TEST_CALC_PARAM values ("CALC1", "param2");

    COMMIT;

    /

    Thank you very much

    Rgds

    XQUERY + MODEL:

    with t as)

    Select calc_id,

    calc_formula,

    Expr,

    r

    of test_calc c,.

    test_params p

    model

    partition (c.calc_id calc_id)

    dimension by (row_number () over (partition by order of 1 c.calc_id) r)

    measures)

    calc_formula,

    Replace (calc_formula, ' /', 'div') expr.

    param_id,

    value

    )

    rules)

    expr [any] order of r desc = regexp_replace (nvl (expr [cv () + 1], expr [cv ()]), param_id [cv ()], value [cv ()])

    )

    )

    Select calc_id,

    calc_formula,

    result xmlcast (xmlquery (expr content return) under the number)

    t

    where r = 1

    /

    CALC_ID CALC_FORMULA RESULT
    ---------- -------------------------------------------------- ----------
    CALC1 (param1 + param2) / (param1 * param2).106666667

    SQL >

    SY.

  • Retrieve the element of the SOAP response

    Hello world

    DB version 11.2.0.4

    Tool: pl/sql developer

    How can I retrieve the element of NfeLinkDanfe by using the xmlQuery? It is a SOAP response...

    With this query, I can retrieve the node "SOAP - ENV:Body", but I Don t know how to get an attribute of the child:

    Select (xmlcast)
    XMLQUERY)
    ' declare namespace SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/"; (:
    declare namespace xx = "GXX_KB001_v2.1.0.0"; (:
    / SOAP-ENV:Envelope/SOAP-ENV:Body/WSRecepcaoNFe.ExecuteResponse'
    from t.a.
    contents of return
    )
    as varchar2 (100)
    )
    of tmp_xml t

    It's the soap response:

    " < SOAP - ENV:Envelope xmlns:SOAP - ENV =" http://schemas.xmlsoap.org/SOAP/envelope/ "
    " container = ' http://www.w3.org/2001/XMLSchema "
    " xmlns:SOAP - ENC =" http://schemas.xmlsoap.org/SOAP/encoding/ "
    " xmlns: xsi =" http://www.w3.org/2001/XMLSchema-instance ">
    < SOAP - ENV:Body >
    < WSRNF. ExecuteResponse xmlns = "GXX_YYY_v1" >
    < Retornows >
    < Message >
    < Code > 500 < / code >
    < message > xxxxxxxx! < / Mensagem >
    < / Mensagem >
    < NotasFiscais >
    < NFe >
    < NfeNumero > 123458 < / NfeNumero >
    < NfeSerie > 123 < / NfeSerie >
    < NfeChaAcesso > 43130806354976000149551230001234581000009575 < / NfeChaAcesso >
    < NfeLinkDanfe > https://hml.com/hnfe055.aspx?RomMsABbcWZNFMWmvpu8Cky0j6BoT8JvrPTqRtREFzYC10ULxD4eFTdP< / NfeLinkDanfe >
    < NfeLinkXML > https://192.168.1.20 HML.com hnfe055.aspx
    ? RomMsABbcWZNFMWmvpu8Cky0j6BoT8JvrPTqRtREFzYaqLRr % 2fXw74KgR< / NfeLinkXML >
    < NfeMensagem / >
    < SitGNFe >
    < SitStatus > 3 < / SitStatus >
    < SitProcessamento > P < / SitProcessamento >
    < / SitGNFe >
    < SitSEFAZ >
    < SitCodigo > 100 < / SitCodigo >
    < SitDescricao > smoking o uso da NF-e < / SitDescricao >
    < / SitSEFAZ >
    < / CHILD >
    < / NotasFiscais >
    < / Retornows >
    < / WSRNF. ExecuteResponse >
    < / SOAP - ENV:Body >
    < / SOAP - ENV:Envelope >

    Thanks in advance!

    Henderson

    Just specify the full path to the item of interest and be careful with the namespaces:

    Select (xmlcast)

    XMLQUERY)

    ' declare SOAP namespace = "http://schemas.xmlsoap.org/soap/envelope/"; (::)

    declare default element names 'GXX_YYY_v1 '; (::)

    /SOAP:envelope / soap: Body / WSRNF. ExecuteResponse/Retornows/NotasFiscais/ENF/NfeLinkDanfe '

    in passing t.object_value

    contents of return

    )

    as varchar2 (100)

    )

    of tmp_xml t.

  • XMLTABLE where condition

    11g 11.2.0.3.0

    Newbie on XMLTABLE XML DB!

    example of XML (person_data.person_data):

    <CstmrPmtStsRpt>
      <GrpHdr>
        <MsgId>99</MsgId>
        <CreDtTm>2013-11-12T08:10:57</CreDtTm>
        <InitgPty>
          <Id>
            <OrgId>
              <Othr>
                <Id>BANK_ID</Id>
                <SchmeNm>
                  <Cd>BANK</Cd>
                </SchmeNm>
              </Othr>
              <Othr>
                <Id>CUST_ID</Id>
                <SchmeNm>
                  <Cd>CUST</Cd>
                </SchmeNm>
              </Othr>
            </OrgId>
          </Id>
        </InitgPty>
      </GrpHdr>
    </CstmrPmtStsRpt>
    

    I want to extract the Id associated with the BANK (and only the Bank Id):

    Asked the SQL output:
    BANK_ID

    So far, I came with:

    SELECT t.column_value
    FROM person_data a,
      XMLTABLE (
        'for $root in /CstmrPmtStsRpt/GrpHdr/InitgPty/Id/OrgId/Othr
         where $root/SchmeNm/Cd = "BANK" 
          return $root/Id'
      passing a.person_data) t;
    

    Which returns

    < id > BANK_ID < /ID >

    Add text() as below:

    SELECT t.column_value
    FROM person_data a,
      XMLTABLE (
        'for $root in /CstmrPmtStsRpt/GrpHdr/InitgPty/Id/OrgId/Othr
         where $root/SchmeNm/Cd = "BANK" 
          return $root/Id/text()'
      passing a.person_data) t;
    

    Returns < no rows returned >

    I know I'm missing something basic here - just need a pointer. Thank you!

    Hello

    I know I'm missing something fundamental here

    No, you do not miss anything, what you have tried must have worked (even if it is not the usual way more to do).

    He must have the bug.

    Fortunately, the solution is quite simple, use an explicit projection via the COLUMNS or XMLQuery clause instead.

    Examples:

    SQL > create table person_data (doc xmltype);

    Table created

    SQL >

    SQL > insert into person_data values)

    2 xmltype (')

    3

    4          99

    5 2013-11 - 12 T 08: 10:57

    6

    7

    8

    9

    10 BANK_ID

    11

    12                    BANK

    13

    14

    15

    16 CUST_ID

    17

    18                    CUST

    19

    20

    21

    22

    23

    24

    25      '));

    1 row inserted

    SQL >

    SQL > SELECT t.bank_id

    from person_data 2A,

    () 3 XMLTABLE

    4 ' $root in/CstmrPmtStsRpt/GrpHdr/InitgPty/Id/OrgId/Othr

    5 where $root/SchmeNm/Cd = 'BANK '.

    6 return $root'

    7 passage a.doc

    path of 8 columns bank_id varchar2 (10) "Id".

    (9) t;

    BANK_ID

    ----------

    BANK_ID

    SQL >

    SQL > select xmlcast)

    2 xmlquery)

    3 ' / CstmrPmtStsRpt/GrpHdr/InitgPty/Id/OrgId/Scout [SchmeNm/DC = 'BANK'] / Id'

    4 passage a.doc

    5 content of return

    6           )

    7 as varchar2 (10)

    8         )

    person_data 9;

    XMLCAST (XMLQUERY('/CSTMRPMTSTS)

    ------------------------------

    BANK_ID

  • pass by value is good or out by value is good.

    Hello

    < number >
    < id = number ' a' > a < / number >
    < number id = "b" > two < / number >
    < id = 'c' number > 10 < / number >
    < a id = "d" number > six < / number >
    < / numbers > '

    Above xml lies in abc table, col xmlcol (type is blob)


    Select XMLCAST (XMLQuery (' for $num in/numbers/number))
    where $num/@id = "a".
    order of $num/@id
    return $num/@id
    pass by value xmltype (xmlcol, nls_charset_id ('AL32UTF8'))
    AS VARCHAR2 (100))
    ABC;

    T1) through value is good or with release of value?

    I use this stored proc.

    Oracel 11 express g

    Yours sincerely

    T1) through value is good or with release of value?

    http://docs.Oracle.com/CD/E11882_01/AppDev.112/e23094/xdb_xquery.htm#CBAHGAJI

    Oracle XML DB supports only passing BY VALUE, not passing BY REFERENCE, so the clause BY VALUE is implicit and can be omitted.
    

Maybe you are looking for

  • Please help with /el capitan iPhoto and iTunes /pet died need photos please

    I'm on an iMac El Capitan 10.11.3 running. I am also running iTunes 12.3.2 I am also running and the iPhone 6 Plus 9.2.1 my pet has just died and I would like to put pictures on my iPhone of assorted external hardeives and rebuild an iPhoto library.

  • Portege R600-10 q keeps freezing after a short period of use

    Hi I have a Portege R600-10, q, It keeps freezing after a short period of use - although if I leave it for a few minutes, sometimes it can be useful.If it is turned on for long enough, it will display a blank screen and the fans will turn on very har

  • Data output DASYLab stop after 10 points

    Let me Preface everything by saying: I'm a novice at this. Now that's the road... I'm having a problem getting more than 10 data points to save in an output file. I'm sure it's a conflict of implementation, but I have no chance to understand. I have

  • Recovery discs - necessary?

    Hello. just a quick question - I have a brand new HP Touch Smart 520 (including rocks I want to put Win8 dev preview on him and be able to recover in the future.)  For recovery to Win7 factory State, just choose drive D to startup or do I have to cre

  • How to recover the DOM Panel

    I do turn a verasion to the trial of cc2015 and my DOM guard Panel disappear while I'm working or some time after being closed, it is absent when I bootA long search in google is not tuen an answer and I can't find a view to turn it on, the only solu