Insert node xmltype

He said this support oracle xml db xquery 1.0 and xquery update 1.0.

I want to insert a node in the xmltype column.

My like this xmltype column:

< + photos >

< default pic = "yes" >

< master > 1.jpg < / master >

1_thumb.jpg < go > < / inch >

< / pic >

< pic >

< master > 2.jpg < / master >

2_thumb.jpg < go > < / inch >

< / pic >

< pic >

< master > 3.jpg < / master >

3_thumb.jpg < go > < / inch >

< / pic >

< pic >

< master > 4.jpg < / master >

4_thumb.jpg < go > < / inch >

< / pic >

< / photos >

My update sql like this: (the xmlquery is see xquery update 1.0)

Update t set t.info XML = xmlquery ('declare variable $e: = $d / / pic [last ()]; insert $e into node $d/pics ' PASSING t.info have "d" RETURNING CONTENT) where t.id =: id and t.info is not null

It went wrong: ORA-18150

There is little reference to the update of xquery sql introduction.

He said this support oracle xml db xquery 1.0 and xquery update 1.0.

XQuery Update is available since version 11.2.0.3, but only the "transform" model of treatment is supported:

SQL> with txml (info) as (
  2    select xmlparse(document
  3  '
  4    
  5      1.jpg
  6      1_thumb.jpg
  7    
  8    
  9      2.jpg
10      2_thumb.jpg
11    
12    
13      3.jpg
14      3_thumb.jpg
15    
16    
17      4.jpg
18      4_thumb.jpg
19    
20  ')
21    from dual
22  )
23  select xmlserialize(document
24           xmlquery(
25             'copy $d := .
26              modify (
27                insert node $d/pics/pic[last()] into $d/pics
28              )
29              return $d'
30             passing t.info
31             returning content
32           )
33           indent
34         )
35  from txml t;

XMLSERIALIZE(DOCUMENTXMLQUERY(
--------------------------------------------------------------------------------

  
    1.jpg
    1_thumb.jpg
  
  
    2.jpg
    2_thumb.jpg
  
  
    3.jpg
    3_thumb.jpg
  
  
    4.jpg
    4_thumb.jpg
  
  
    4.jpg
    4_thumb.jpg
  

There is little reference to the update of xquery sql introduction.

XQuery and Oracle XML DB

Querying and updating of XML data

Best practices for XQuery in Oracle Database 12c

Tags: Database

Similar Questions

  • XQuery insert node and assign the value based on an XPATH expression

    Hello

    I am trying to write a function that receives an XML as input parameters and return updated XML output

    -nodes are removed from the input XML code

    -a node must be inserted and the node value must be 1 or 0, based on an XPATH expression

    I discovered how to remove nodes, I discovered how to insert a new node, but I can not set the value of the conditionally inserted node an XPATH expression.

    Here's my current procedure and below a sample of one XML of entry. I use Oracle 12 c.

    CREATE OR REPLACE FUNCTION STRIP_XML
    (
      IN_XML IN SYS.XMLTYPE
    ) RETURN SYS.XMLTYPE AS
    p_result XMLType;
    BEGIN
      select
          xmlquery(
             'declare default element namespace "http://mad.evs.com/search"; (: :)
              copy $d := .
              modify (
      delete node $d//MainCategory/@logId,
               delete node $d/MainCategory/@id,
    -- a lot more of those delete node
     -- insert a node, but the value 1 is conditional
               insert node <DMZ>1</DMZ> after $d/MainCategory/SDataSection/EventDate)
              return $d'
            passing in_xml
            returning content
            ) into p_result
            from dual;
    
    
      RETURN p_result;
    END STRIP_XML;
    

    The condition for the value of is


    HASPATH (//DigitalAssets/DigitalAsset [@ available = "true" and @videoFormatId = "11"] / VideoLocations/Videorental [@typeId = "8"]) then 1 else 0


    It is complex because DigitalAssets/DigitalAsset is a collection. Here is an example of an XML to entry



    <MainCategory xmlns="http://mad.evs.com/search" id="9" logId="3349" logType="3">
      <Name>Sport</Name>
      <Serie id="163" externalId="557">
      <TitleAKA>UCL 2006/07</TitleAKA>
      <DigitalAssets available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3">
         <DigitalAsset available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3" videoFormatId="3">
            <VideoLocations>
                <VideoLocation id="3" path="003349MA.mxf" typeId="1" locationId="1" priority="0"/>
                <VideoLocation id="3" path="003349MA.mxf" typeId="2" locationId="1" priority="0"/>
                <VideoLocation id="3" path="003349MA.mxf" typeId="5" locationId="1" priority="0"/>
             </VideoLocations>
          </DigitalAsset>
          <DigitalAsset available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3" videoFormatId="11">
             <VideoLocations>
                <VideoLocation id="101" path="003349MA.mpg" typeId="1" locationId="1" priority="0"/>
                <VideoLocation id="101" path="003349MA.mpg" typeId="2" locationId="1" priority="0"/>
                <VideoLocation id="101" path="003349MA.mpg" typeId="8" locationId="1" priority="0"/>
             </VideoLocations>
          </DigitalAsset>
      </DigitalAssets>
      <SDataSection xmlns="http://mad.evs.com/search">
        <EventDate>2006-08-09</EventDate>
        <LogType>3</LogType>
      </SDataSection>
    </MainCategory>
    


    In this case, because HASPATH expression could be set to true, the value of the added node must be 1.


    Any help or advice how I should fight against that would be appreciated. I have no experience with XML and XQuery, I create my function through from trial and error of the doc.


    Thanks and regards, Pierre

    Hi Pierre,.

    You can use the if-then-else statement, like this:

    Insert the node

    {

    If ($d/MainCategory/DigitalAssets/DigitalAsset[@available="true' and @videoFormatId = '11'] / VideoLocations/Videorental [@typeId = '8'])

    then 1

    0 otherwise

    }

    After $d, MainCategory, SDataSection, EventDate

    XSLT can be an alternative to the XQuery Update in this case.

  • [11g] ORA-31061/ORA-19202 - how to insert data xmltype table/validation of the schema (just well formed)

    Hello

    Oracle Database 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production

    PL/SQL Release 11.2.0.3.0 - Production

    CORE Production 11.2.0.3.0

    AMT for Linux: Version 11.2.0.3.0 - Production

    NLSRTL Version 11.2.0.3.0 - Production

    Here's the demo program:

    ==============================

    create a global temporary table GTT_Test(data xmltype) validation delete rows;

    - and run this

    declare

    v_data xmltype.

    Start

    -It does not work

    /*

    v_data: = xmltype ("< itf:meta > < node / > < / itf:meta > '");

    */

    - but it works

    v_data: = xmltype)

    XMLDATA = > ' < my: meta > < node / > < / my: meta > ',

    schema = > null,

    validated = > 0,

    correct = > 1);

    - but try to insert into the table in the same way fails again:

    insert into GTT_Test (data)

    values (xmltype)

    XMLDATA = > ' < my: meta > < node / > < / my: meta > ',

    schema = > null,

    validated = > 0,

    correct = > 1));

    end;

    ==============================


    It translates errors ORA above and suspicion: "prefix 'my' is not declared".


    I need to create the TWG somehow different to accept without diagram validation?


    -Thanks!


    Kind regards

    Frank

    Hello.

    Try to declare to your XML namespace.

    for examplehttp://youaddress">

    "If you don't have a schema, try xmlns: my =" "(espace en blanc)."

  • Add the xmltype attribute node

    How can I add an attribute node to xml in an xmltype?
    Say that I
    declare
      t_xml xmltype;
    begin
      t_xml := xmltype( '<x a="1"/>' );
    end;
    How can I manipulate this variable t_xml become
    <x a="1" b="2"/>
    Anton

    Depends on the version.

    Before 11.2.0.3:

    SQL> with t as (  select xmltype('') as t_xml from dual )
      2  select insertchildxml(
      3           t_xml
      4         , '/x'
      5         , '@b'
      6         , '2'
      7         )
      8  from t;
    
    INSERTCHILDXML(T_XML,'/X','@B'
    --------------------------------------------------------------------------------
    
     
    

    On 11.2.0.3, by using XQuery Update:

    select /*+ no_xml_query_rewrite */
           xmlquery(
            'copy $d := .
             modify ( insert node attribute b {$val} into $d/x )
             return $d'
            passing t_xml
                  , '2' as "val"
            returning content
           )
    into t_xml
    from dual
    ;
    

    (not tested, but should be close)

    Marco Gralike wrote:
    You should be able to build up the little together 'back' in a dynamic method, but for now, don't ask me how (mark)?

    The generic approach would require market the entire tree down recursively to the copy existing nodes and add the new in the right place.
    Although XQuery (without involving XQUF) can do it, it's more of a task for XSLT:

    SQL> with t as (  select xmltype('') as t_xml from dual )
      2  select xmltransform(
      3           t_xml
      4         , xmlparse(document
      5  '
      6    
      7    
      8    
      9      
     10        
     11      
     12    
     13    
     14      
     15        
     16      
     17    
     18  '
     19           )
     20         , q'{att="'2'"}'
     21         )
     22  from t;
    
    XMLTRANSFORM(T_XML,XMLPARSE(DO
    --------------------------------------------------------------------------------
    
    
     
    
  • XMLTYPE string buffer too small

    I do the following:

    DECLARE

    xmlValue CLOB

    : = ' < HTNG_HotelRoomStatusSearchRS > < success > < / success > < errors > < error Type = '0' doc 'None' = > < / error > < / errors >

    < RoomInformationList > < TPA_Extensions > < TPA_Extension >

    < UNITI > < / UNITI > < / TPA_Extension > < / TPA_Extensions >

    < / RoomInformationList > < / HTNG_HotelRoomStatusSearchRS > ';

    XMLTYPE x_xml;

    NewValue VARCHAR2 (2000): = ' < UNIT_NUM UNIT = "ABCD" / > ";

    BEGIN

    x_xml: = xmltype (xmlvalue);

    FOR I IN (SELECT col1

    OF xml_modify

    )

    LOOP

    SELECT XMLQUERY (' copy $i: $p1 = edit)

    (for $j to $i / / TPA_Extensions/TPA_Extension/States)

    back insert node $p2 before $j)

    Return $i "PASSAGE x_xml AS"p1", xmltype (i.col1) AS 'p2' RETURN CONTENT)

    IN x_xml

    FROM DUAL;

    END LOOP;

    x_xml: = x_xml. DELETEXML ('/ / STATES ');

    Dbms_output.put_line (x_xml.getstringval ());

    END;

    BTW, there is very little effective insertion of nodes like this in a loop.

    Build the fragment in a go with XMLAGG on the XML_MODIFY table, and then insert that fragment using XQuery Update.

    You can even remove the UNITI node within the same expression:

    DECLARE
    
      x_xml  xmltype := xmltype(
      '
    
    
    ');
    
      x_units  xmltype;
    
    BEGIN
    
      select xmlagg(xmlparse(content col1))
      into x_units
      from xml_modify
      --where rownum < 10
      ;
    
      SELECT XMLQUERY(
               'copy $i := $p1
                modify (
                  for $j in $i/HTNG_HotelRoomStatusSearchRS/RoomInformationList/TPA_Extensions/TPA_Extension/UNITI
                  return (
                    insert node $p2 before $j
                  , delete node $j
                  )
                )
                return $i'
               PASSING x_xml AS "p1"
                     , x_units AS "p2"
               RETURNING CONTENT
             )
      INTO x_xml
      FROM DUAL;
    
      --x_xml := x_xml.DELETEXML ('//UNITI');
      --DBMS_OUTPUT.put_line(x_xml.getclobval(1,2));
    
    END;
    /
    
  • XMLQUERY Multiple inserts

    I have the following:

    DECLARE

    xmlValue CLOB

    : = ' < HTNG_HotelRoomStatusSearchRS > < success > < / success > < errors > < error Type = '0' doc 'None' = > < / error > < / errors >

    < RoomInformationList > < TPA_Extensions > < TPA_Extension >

    "" < UNIT_NUM UNIT = "pm_unit_num" UNIT_TYPE = "pm_unit_type_desc" HSK_DESC = "CLN" ROOM_STATUS = "EMPY" STATUS_CODE = "HERE" ARRIVAL_DATE = DEPARTURE_DATE "now" = "THEN" RESV_TYPE ="RT" DRI_PROP_ID = "DPI" RESV_NUM = "RN" CREATE_DATE = "CD" MC_PROPERTY_CODE = "MPC" HOTEL_DATE ="HD" SERVICE_CODE = 'SC' > < / UNIT > < / TPA_Extension > < / TPA_Extensions >

    < / RoomInformationList > < / HTNG_HotelRoomStatusSearchRS > ';

    XMLTYPE x_xml;

    CLOB y_xml;

    BEGIN

    x_xml: = xmltype (xmlvalue);

    BECAUSE me in 1... 2

    LOOP

    SELECT XMLQUERY (' copy $tmp: = change the node the insert)

    < UNIT_NUM UNIT = "ABCD" / >

    After $tmp / / TPA_Extensions/TPA_Extension/UNIT

    return $tmp' PASSING x_xml RENVOYANT CONTENT)

    IN x_xml

    FROM DUAL;

    y_xml: = x_xml.getstringval (); -Thought that the reset would fix it. I think it has to do with more than one < UNIT / >

    x_xml: = xmltype (y_xml);

    END LOOP;

    Dbms_output.put_line (x_xml.getstringval ());

    END;

    When I run the present for an insert, it works very well. When I try 2 times I get this error.

    ORA-18104: XUTY0005 - invalid target for INSERTION expression

    ORA-06512: at line 17 level

    It worked.

    DECLARE

    xmlValue CLOB

    := '

    ';

    XMLTYPE x_xml;

    NewValue VARCHAR2 (2000): = '';

    BEGIN

    x_xml: = xmltype (xmlvalue);

    BECAUSE me in 1... 10

    LOOP

    SELECT XMLQUERY (' copy $i: $p1 = edit)

    (for $j to $i / / TPA_Extensions/TPA_Extension/States)

    back insert node $p2 before $j)

    Return $i "PASSAGE x_xml AS"p1", xmltype (newvalue) AS"p2"RETURN CONTENT)

    IN x_xml

    FROM DUAL;

    NewValue: = '';

    END LOOP;

    x_xml: = x_xml. DELETEXML ('/ / STATES ');

    Dbms_output.put_line (x_xml.getstringval ());

    END;

  • Replacement of the nodes with duplicates

    I can't find out how to write an XQuery query which can essentially 'jump' a replacement when I said to. I don't know who makes no sense, so here's a better explanation.

    I have an XML file that is stored in an Oracle XML DB that looks like this:
    <bookstore>
        <book title="Analytical Chemistry" publish_date="198710">
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Particle Physics" publish_date="199202">
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Applied Biophysics" publish_date="201005">
           <author>...
           <publisher>....
           <etc.>
        </book>
    </bookstore>
    We get the update commands that look like the same thing, with a 'command' attached to add the book to the store or drop:
    <bookstore>
        <book title="Analytical Chemistry" publish_date="199210">
           <order>merge</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Particle Physics" publish_date="199202">
           <order>drop</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Chaos Theory" publish_date="199102">
           <order>merge</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
    </bookstore>
    The rule is should I replace or add a book in the store if I have a book of the same title, and the order is "merge", or drop it if the order is to 'drop '. I have a request XQuery Update function now makes what looks like this:
    declare updating function local:book_merge($old, $book_merge)
    {
         for $orderEntr in $book_merge/book
         let $chgCd := $orderEntr/order
         let $orderTitle := $orderEntr/@title
            let $oldBooks := $old/bookstore
         let $oldBookEntr := $oldBooks/book[@title=$orderTitle]
         return
            if( $chgCd = "drop" and exists($oldBookEntr) )
            then delete node $oldBookEntr
            else if( exists($oldBookEntr) )
            then replace node $oldBookEntr with $orderEntr
            else insert node $orderEntr into $oldBooks
    };
    This works very well for commands like above, but once from time to time, we receive a command like this:
    <bookstore>
       <book title="Analytical Chemistry" publish_date="199210">
           <order>merge</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Analytical Chemistry" publish_date="199210">
           <order>merge</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Particle Physics" publish_date="199202">
           <order>drop</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
        <book title="Chaos Theory" publish_date="199102">
           <order>merge</order>
           <author>...
           <publisher>....
           <etc.>
        </book>
    </bookstore>
    Notice how the first entry is duplicated. In this case, the requirement must only enter the book in the library once. Can someone give me an idea of how I would go about implementing that? I am struggling to understand how to ask the right question, so please forgive me.

    You can add a predicate that will filter the next (or previous) duplicates of a given input:

    where not($orderEntr/following-sibling::book[@title = $orderTitle])
    

    Full test case:

    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> create table tmp_xml of xmltype;
    
    Table created.
    
    SQL> insert into tmp_xml values (
      2  xmltype('
      3      
      4         XXX
      5         
      6      
      7      
      8         YYY
      9         
     10      
     11      
     12         ZZZ
     13         
     14      
     15  ')
     16  );
    
    1 row created.
    
    SQL> var orders clob
    SQL> begin
      2
      3   :orders := '
      4      
      5         merge
      6         XXX
      7         123
      8      
      9      
     10         merge
     11         XXX
     12         123
     13      
     14      
     15         drop
     16         YYY
     17         
     18      
     19      
     20         merge
     21         ZZZ-2
     22         
     23      
     24  ';
     25
     26  end;
     27  /
    
    PL/SQL procedure successfully completed.
    
    SQL> set long 5000
    SQL> set pages 100
    SQL>
    SQL> select /*+ no_xml_query_rewrite */
      2         xmlserialize(document
      3           xmlquery(
      4           'copy $d := $old
      5            modify (
      6              for $orderEntr in $orders/bookstore/book
      7              let $chgCd := $orderEntr/order
      8              let $orderTitle := $orderEntr/@title
      9              let $oldBooks := $d/bookstore
     10              let $oldBookEntr := $oldBooks/book[@title = $orderTitle]
     11              where not($orderEntr/following-sibling::book[@title = $orderTitle])
     12              return
     13                 if( $chgCd = "drop" and exists($oldBookEntr) )
     14                   then delete node $oldBookEntr
     15                 else if( exists($oldBookEntr) )
     16                        then replace node $oldBookEntr with $orderEntr
     17                      else insert node $orderEntr into $oldBooks
     18            )
     19            return $d'
     20           passing object_value as "old"
     21                 , xmlparse(document :orders) as "orders"
     22           returning content
     23           )
     24           indent
     25         ) as result
     26  from tmp_xml ;
    
    RESULT
    --------------------------------------------------------------------------------
    
      
        merge
        XXX
        123
      
      
        ZZZ
        
      
      
        merge
        ZZZ-2
        
      
    
    

    It's another question, you probably already have the answer: I guess you must also remove the nodes of the newly merged books?

  • HOW to add an attribute to the existing node?

    Hello

    I have a question - is possible to add a NEW attribute to existing xml node registered in xmltype?

    I found no such a possibility.

    I need to use the update! :)

    I have: < tag > < tag2 / > < tag / >

    I want to have < tag value = 1 > < tag2 / > < tag / >

    THANKS IN ADVANCE! :)

    With insertChildXML:

    SQL> with t as (
      2    select xmltype('') doc
      3    from dual
      4  )
      5  select insertChildXML(doc, '/tag', '@value', 1)
      6  from t
      7  ;
    
    INSERTCHILDXML(DOC,'/TAG','@VA
    --------------------------------------------------------------------------------
    
     
    

    Alternatively, in 11.2.0.3, updated XQuery:

    select xmlquery(
    'copy $d := $doc/tag
     modify ( insert node attribute value {$val} into $d )
     return $d'
     passing t.doc as "doc"
           , 1 as "val"
     returning content
    )
    from t
    ;
    
  • upsert xmltype data xpath - missing something obvious?

    Version: 10.2.0 * 2 * EA

    I'm doing a upsert (update / insert) of an xmltype for a given xpath.

    The xml data is passed as an xmltype, xpath is a string (varchar2), the new value is a string, varchar2.

    If the node specified by the xpath expression exists it is trivial using updatexml; of course if the node is not nothing happens. I can verify the existence of nodes using is node, but I just take off, trying to figure out how to insert the node.

    All the APIs I can find who to insert XML (APPENDCHILDXML, INSERTXMLBEFORE, INSERTCHILDXML) do not take an xpath but require an xmltype. Which means that if I'm reading this right I have no other choice to the parse varchar2 string xpath to create an xmltype (ugh!).

    I can't find any API that takes an xpath as a varchar2 and a value and gives me an xmltype. Ideally I want same, here an API that returns the XML updated which took the set xpath to update (or inserted if it did not exist) with the new value.

    I'm not an XML expert but I'm pretty handy with SQL and PL/SQL. For me this seems incredibly heavy just to do something as mundane as an upsert, so I hope I'm missing something obvious!

    Can soemone please put me everything right with a pointer or an example?

    On top of the XML uses namespaces, but they are not registered, there is no record of current schema.

    Marco Gralike wrote:
    Could not be done through XQuery, although the version of database doesn't really help...

    It would be possible with a dynamic, but 'painful' XQuery with a static expression expression because it would require parsing the XPath expression and rebuild the entire document of entry with the necessary adaptations.
    I think XSLT would be more effective in this case.

    Perhaps, one day, when the database is XQuery Update Facility, we will be able to do:

    copy $a := $doc/Address
    modify (
      if ($a/zip)
        then replace value of node $a/zip with "12345"
        else insert node element zip {"12345"} into $a
    )
    return $a
    

    user12083137 wrote: for me, from a SQL background, I can't believe this simple case is simply not covered.

    Perhaps not as simple as it sounds. :)

    The feature can be simulated by an IF/THEN/ELSE logic, or a DELETE/INSERT sequence.
    For example:

    case when existsNode(doc, xpath) = 1
      then updateXML(
             doc
           , xpath || '/text()'
           , somevalue
           )
      else appendchildxml(
             doc
           , substr(xpath, 1, instr(xpath, '/', -1)-1)
           , xmlelement(
               evalname(substr(xpath, instr(xpath, '/', -1)+1))
             , somevalue
             )
           )
    end
    

    or,

    appendChildXML(
      deleteXML(doc, xpath)
    , substr(xpath, 1, instr(xpath, '/', -1)-1)
    , xmlelement(
        evalname(substr(xpath, instr(xpath, '/', -1)+1))
      , somevalue
      )
    )
    
  • Why the nodes are placed on web sites that I discovered with fire fox but not other browsers

    When you view the web page with fire fox is someone changing words and inserting nodes on the site. This does not happen with chrome or explorer. When I inspect the element it is HTML not allowed more written on the site. I have remove the node (a commercial that redirects the browser), but they pop up.

    You can check the suspicious extensions or recently installed unknowns.

    Make a check of malware with several malware scanning of programs on the Windows computer.
    Please scan with all programs, because each program detects a different malicious program.
    All of these programs have free versions.

    Make sure that you update each program to get the latest version of their databases before scanning.

    Alternatively, you can write a check for an infection rootkit TDSSKiller.

    See also:

  • Update of the data in the Table using XMLTYPE DATA

    I did insertions using XMLTYPE data but have never done it and update. Can someone give me some advice?

    PROCEDURE ADD_LABORDER_CODES)

    IN_ORDERCODESXML IN CLOB DEFAULT NULL,

    Number of OUT OUT_AFFECTEDROWS

    )

    AS

    X SYS. XMLTYPE;

    BEGIN

    X: = SYS. XMLTYPE. CREATEXML (IN_ORDERCODESXML);

    INSERT INTO MAINT_LABORD_CODES)

    INSERT INTO MAINT_LABORD_CODES)

    LABORD_CODE_ID,

    COMPENDIUM_ID,

    ORDER_CODE,

    ORDER_DESC,

    ACTIVE,

    TIMESTAMP,

    MODIFIED_BY)

    SELECT MLOCDS_SEQ. NEXTVAL,

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/COMPENDIUM_ID') AS COMPENDIUM_ID,

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/ORDER_CODE') AS ORDER_CODE,

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/ORDER_DESC') AS ORDER_DESC,.

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/LOINC_CODE') AS LOINC_CODE,

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/ACTIVE') AS ACTIVE.

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/TIMESTAMP') AS TIMESTAMP.

    EXTRACTVALUE (VALUE (MLOC), '/ ORDERCODE/MODIFIED_BY') AS MODIFIED_BY

    TABLE (XMLSEQUENCE (EXTRACT(X,'/ORDERCODES/ORDERCODE'))) NMCO;

    OUT_AFFECTEDROWS: = NUMBER OF ROWS SQL %;

    EXCEPTION

    WHILE OTHERS THEN

    dbms_output.put_line (SQLERRM);

    RAISE_APPLICATION_ERROR (-20001, SQLERRM);

    END;

    Example of use of the FUSION-

    If the line exists in the target table (based on the COMPENDIUM_ID and ORDER_CODE values), the UPDATE is, if not to INSERT:

    declare
    
      in_ordercodesxml  clob :=
      '
      
        500
        696231
        ABO Group & Rh Type
        NULL
        12345
        Y
        2014-08-13
        1
      
    ';
    
    begin
    
      merge into maint_labord_codes t
      using (
        select compendium_id
             , order_code
             , order_desc
             , loinc_code
             , active
             , timestamp
             , modified_by
        from xmltable('/ORDERCODES/ORDERCODE'
               passing xmltype(in_ordercodesxml)
               columns COMPENDIUM_ID    number(10)    path 'COMPENDIUM_ID'
                     , ORDER_CODE       varchar2(50)  path 'ORDER_CODE'
                     , ORDER_DESC       varchar2(250) path 'ORDER_DESC'
                     , LOINC_CODE       varchar2(10)  path 'LOINC_CODE'
                     , ACTIVE           varchar2(1)   path 'ACTIVE'
                     , TIMESTAMP        date          path 'TIMESTAMP'
                     , MODIFIED_BY      number(10)    path 'MODIFIED_BY'
             )
      ) x
      on (     t.compendium_id = x.compendium_id
           and t.order_code = x.order_code )
      when matched then update
        set t.order_desc = x.order_desc
          , t.loinc_code = x.loinc_code
          , t.active     = x.active
          , t.timestamp  = x.timestamp
          , t.modified_by = x.modified_by
      when not matched then insert
      (
        labord_code_id
      , compendium_id
      , order_code
      , order_desc
      , loinc_code
      , active
      , timestamp
      , modified_by
      )
      values (
        mlocds_seq.nextval
      , x.compendium_id
      , x.order_code
      , x.order_desc
      , x.loinc_code
      , x.active
      , x.timestamp
      , x.modified_by
      );
    
    end;
    /
    

    Also note that I used XMLTABLE instead of TABLE/XMLSEQUENCE, which is much easier to use (and not deprecated in the latest versions).

    You have not precisely the date format in the TIMESTAMP element so I assumed a conform to W3C.

    If you have a problem with this part, return to a projection of VARCHAR2 and use TO_DATE with actual size.

  • Insert the XML document with values of characters &lt; or &gt;

    Hello world

    Used Oracle: version 11.2.0.3.0

    I want to insert an XML document in a binary XML field. But for an element, the value includes characters such as > or <.

    Here's an example query:

    Update / * + no_xml_query_rewrite * / ms2 set mstag = XMLQuery (' copy $tmp: = .modify (for $i in $tmp/tags/fields[@id="MS"]))

    back insert nodes (< value > TEST\n & lt; Address1 & gt; < / value >) in $i) return $tmp' from mstag content back) where psid = 5900;

    But because we're using the character & in a SQL query, this request has failed. We invited to specify the 2 values.

    So, what is the way of giving the < Address1 > value to the value of the element in the example?

    Thanks in advance

    The command is not really "fail" in itself. It is just the tool that you are using recognizes '&' characters and treats the following identifiers as replacement variables.

    What tool do you use?

    For example, in SQL * Plus you can disable this behavior through the SET DEFINE OFF or SET SCAN OFF command.

  • Addition of several xml using Insertxmlbefore in a single query. Help, please.

    Oracle version

    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

    I have an xml where I need to insert a new xml basedupon the partyID.

    for each partyid in the need to xmoutput to insert representative data.

    with t as (
    select 1 source_no , xmltype('<report>
                       <partyReported partyId="1">
                         <name> TEST123</name>
                      </partyReported>
                      <partyReported partyId="2">
                         <name> TEST456</name>
                      </partyReported>
                   </report>')
                   xmloutput
                   from dual
                )
              ,
              t_member as (
               select 1 candidate_no, xmltype('<Representative>
                                           <name> rep123 </name>
                                  </Representative>') rep_xml from dual
              union all
              select 2 , xmltype('<Representative>
                                           <name> rep456 </name>
                                  </Representative>') from dual
            )
            , t_rep_member as(
            SELECT
              source_no
            , X.*
            , xmloutput
         FROM
              t
            , XMLTABLE ('/report/partyReported' passing xmloutput COLUMNS candidate_no INTEGER PATH '@partyId', candidate_idx FOR ordinality ) AS X
         )
         , all_data
         as (
         select sourcE_no, a.candidate_no, xmloutput, rep_xml from t_rep_member a, t_member b
         where a.candidate_no = b.candidate_no
         )
         select source_no, MergeRepXml(repxml(candidate_no,rep_xml,xmloutput)) final_xml from all_data
         group by sourCe_no;
    
    

    source_no, candidate_no, candidate_idx, xmloutput
    
    1    1    1    "<report>                   <partyReported partyId="1">                     <name> TEST123</name>                  </partyReported>                   <partyReported partyId="2">                     <name> TEST456</name>                  </partyReported>                </report>"
    1    2    2    "<report>                   <partyReported partyId="1">                     <name> TEST123</name>                  </partyReported>                   <partyReported partyId="2">                     <name> TEST456</name>                  </partyReported>                </report>"
    
    
    
    

    I solved this problem, but I get an error message when I try to do 1000 of them.

    ERROR:

    ORA-22813: value of the operand is greater than the limits of the system

    create or replace
    type RepXml as object( candidate_no number, rep_xml xmltype, output xmltype)
    /
    create or replace
    type RepXmltab as table of RepXml
    /
    
    
    
    
    
    create or replace
    type MERGEREP as object
    (
      -- string varchar2(4000),                  -- deleted
      val_table  RepXmltab ,           -- added
    
    
      static function ODCIAggregateInitialize
        ( sctx in out MERGEREP )
        return number ,
    
      member function ODCIAggregateIterate
        ( self  in out MERGEREP ,
          value in     RepXml
        ) return number ,
    
      member function ODCIAggregateTerminate
        ( self        in  MERGEREP,
          returnvalue out xmltype,
          flags in number
        ) return number ,
    
      member function ODCIAggregateMerge
        ( self in out MERGEREP,
          ctx2 in     MERGEREP
        ) return number
    );
    
    
    create or replace
    type body MERGEREP
    is
    
      static function ODCIAggregateInitialize
      ( sctx in out MERGEREP )
      return number
      is
      begin
    
         sctx := MERGEREP( repxmltab(null,null,null) );
         --val_table:= repxmltab(null);
    
        return ODCIConst.Success ;
    
      end;
    
      member function ODCIAggregateIterate
      ( self  in out MERGEREP ,
        value in     RepXml
      ) return number
      is
      begin
    
        self.val_table.extend;
        self.val_table(self.val_table.count) := value;
    
        return ODCIConst.Success;
      end;
    
      member function ODCIAggregateTerminate
      ( self        in  MERGEREP ,
        returnvalue out xmltype ,
        flags       in  number
      ) return number
      is
    
        v_data  xmltype ;
    
      begin
    
    v_data:= null;
    
    for x in (
         select candidate_no,rep_xml,output
          from   table(val_table)
          )
          loop
          v_data:= x.output;
    
          end loop;
               
       
        for x in
        (
    select candidate_no,rep_xml,output
          from   table(val_table)
          )
        loop
        select insertxmlbefore(v_data,'/report/partyReported[@partyId="'||x.candidate_no||'"]', x.rep_xml) into v_data from dual;
    null;
        end loop;
    
        returnValue := ( v_data) ;
    
    v_data:= null;
    
        return ODCIConst.Success;
    
      end;
    
      member function ODCIAggregateMerge
      ( self in out MERGEREP ,
        ctx2 in     MERGEREP
      ) return number
      is
      begin
    
        for i in 1 .. ctx2.val_table.count
        loop
          self.val_table.extend;
          self.val_table(self.val_table.count) := ctx2.val_table(i);
        end loop;
    
    
    
        return ODCIConst.Success;
    
            end;
      end;
    /
    
    create or replace
    function MergeRepXml
      ( input RepXml )
      return xmltype
      deterministic
      parallel_enable
      aggregate using MERGEREP
    ;
    /
    
    

    With my limited knowledge, I tried to write recursive with clause and achieve the expected results, but many lines are displayed.

    WITH
         t1 AS
         ( SELECT * FROM aps_extendedoutput WHERE source_no = 261177
         )
         --     select * from t1;
       , t AS
         (SELECT
              source_no
            , X.*
            , xmloutput
         FROM
              t1
            , XMLTABLE ('/report/role/partyReported' passing xmloutput COLUMNS candidate_no INTEGER PATH '@partyId', candidate_idx FOR ordinality ) AS X
         )
         --     select * from t;
       , all_data AS
         (SELECT
              /*+ materialize */
              t.candidate_no
            , rep_xml
            , source_no
            , t.candidate_no
            , xmloutput
         FROM
              t
            , aps_reppartyxml t_p
         WHERE
              t.candidate_no = t_p.candidate_no
         )
         --   select * from all_data;
       ,recursive_data(candidate_i, xmloutput, source_no, candidate_no) AS
         (SELECT
              1 candidate_i
              , xmloutput
            ,  source_no
            , 0 candidate_no
         FROM
             t1
         UNION ALL
         SELECT
              candidate_i + 1
              , insertxmlbefore(rd.xmloutput,'/report/role/partyReported[@partyId="'
              ||ad.candidate_no
              ||'"]', ad.rep_xml) xmloutput
            , ad.source_no
            , rd.candidate_no
         FROM
              all_Data ad
            , recursive_data rd
         WHERE
              ad.sourcE_no        = rd.source_no and
               candidate_i     < 3
         )
    SELECT *  FROM recursive_data;
    
    

    for example

    SQL> create table t_member as (
      2  select 1 candidate_no, xmltype('
      3                                rep123 
      4                      ') rep_xml from dual
      5  union all
      6  select 2 , xmltype('
      7                                rep456 
      8                      ') from dual
      9  );
    
    Table created.
    
    SQL>
    SQL> set long 5000
    SQL>
    SQL> with t (source_no, xmloutput) as (
      2    select 1
      3         , xmltype('
      4                      
      5                          TEST123
      6                      
      7                      
      8                          TEST456
      9                      
     10                   ')
     11    from dual
     12  )
     13  select t.source_no
     14       , xmlserialize(document
     15           xmlquery(
     16             'copy $d := .
     17              modify (
     18                for $i in $d/report/partyReported
     19                  , $j in fn:collection("oradb:/DEV/T_MEMBER")/ROW
     20                where $j/CANDIDATE_NO = $i/@partyId
     21                return insert node $j/REP_XML/* before $i
     22              )
     23              return $d'
     24             passing t.xmloutput
     25             returning content
     26           )
     27           indent
     28         ) as final_xml
     29  from t ;
    
     SOURCE_NO FINAL_XML
    ---------- --------------------------------------------------------------------------------
             1 
                 
                    rep123 
                 
                 
                    TEST123
                 
                 
                    rep456 
                 
                 
                    TEST456
                 
               
    
  • Oracle XML INSERTCHILDXML

    Hello

    I want to add a child node of XML in an XML column in the dependence, when the top element has a special attribute value. The XML Document looks like this:

    < root_element >

    <>node

    < name subnode = 'a' / >

    < name subnode = 'b' / >

    < name subnode = 'c' / >

    < / node >

    < / root_elemnt >

    If I want to insert a child node for the subnode with the name of c, so that it looks like after:

    < root_element >

    <>node

    < name subnode = 'a' / >

    < name subnode = 'b' / >

    < name subnode = 'c' >

    < new_element / >

    < / subnode >

    < / node >

    < / root_elemnt >

    I tried the following SQL statement, but it did not work:

    update from table_a a SET a.DOCUMENT =

    INSERTCHILDXML (a.DOCUMENT, ' / root_element/node/subnode/@name=c 'new_element", XMLTYPE ('blabla < new_element > < / new_element > '))

    where...;

    The statement is executable, I get no errors-XPATH-Expression...

    I hope you can help me.

    Heiko

    INSERTCHILDXML (a.DOCUMENT, ' / root_element/node/subnode/@name=c 'new_element", XMLTYPE ('Bond'))

    Besides what you have posted is not syntactically correct, you also have the parent XPath expression wrong.

    You want a predicate, not a step of the attribute.

    Here is the correct statement using insertChildXML:

    update table_a a
    set a.doc =
        insertchildxml(
          a.doc
        , '/root_element/node/subnode[@name="c"]'
        , 'new_element'
        , xmlparse(document 'blabla')
        )
    where id = 1 ;
    

    However, Oracle XML DML functions such as insertChildXML are deprecated.

    Use XQuery Update:

    SQL> drop table table_a purge;
    
    Table dropped
    
    SQL> create table table_a (id int, doc xmltype);
    
    Table created
    
    SQL>
    SQL> insert into table_a values (1, xmlparse(document
      2  '
      3       
      4            
      5            
      6            
      7       
      8  '));
    
    1 row inserted
    
    SQL> commit;
    
    Commit complete
    
    SQL>
    SQL> update table_a a
      2  set a.doc =
      3      xmlquery(
      4        'copy $d := .
      5         modify ( insert node $new into $d/root_element/node/subnode[@name="c"] )
      6         return $d'
      7        passing a.doc
      8              , xmlparse(document 'blabla') as "new"
      9        returning content
     10      )
     11  where id = 1 ;
    
    1 row updated
    
    SQL>
    SQL> select xmlserialize(document doc) from table_a where id = 1;
    
    XMLSERIALIZE(DOCUMENTDOC)
    --------------------------------------------------------------------------------
    
      
        
        
        
          blabla
        
      
    
    
  • XQuery and relational queries with the RAW data

    So, I have a table like this setting:
    CREATE TABLE book_frag
    (
      book_id RAW(16),
      xpath_id INT,
      last_modified_ts TIMESTAMP,
      created_date TIMESTAMP,
      book_data XmlType,
      PRIMARY KEY(book_id, xpath_id),
      FOREIGN KEY (book_id) REFERENCES book(book_id),
      FOREIGN KEY (xpath_id) REFERENCES book_xpath(xpath_id)
    );
    
    CREATE TABLE book_xpath
    (
      xpath_id INT,
      book_element_name VARCHAR2(32),
      PRIMARY KEY(xpath_id)
    );
    I am trying a query which will regroup the different XMLTypes book_frag into one. If I use this query, it works, but it is slow and sometimes times out:
    SELECT 
        e.book_id,
        
        e.title_txt,
        e.subj_txt,
        
        e.target_mkt,
        e.target_lcl_mkt,
        
        e.catg,
        e.lang_code,
        e.out_of_stock_reas,
        
        e.sucsr_title,
        e.sucsr_sub_txt,
        
        e.orig_copy_ref,
        e.orig_subj_txt,
        
        XMLQuery(
        'declare namespace invtdata="http://www.mrbook.com/InventoryData";
        
         copy $invtData := $orig/invtdata:inventory
         
         modify
         (
           for $bkRow in fn:collection("oradb:/BOOKSCHEMA/BOOK_FRAG")
           let $bk := $mpfRow/ROW/BOOK_DATA/node()
           where xs:string($bkRow/ROW/ID)=$bookId
           return insert node $bk into $invtData
         ) return $invtData'
         PASSING XmlType('<inventory xmlns="http://www.mrbook.com/InventoryData" />') AS "orig",
         CAST(e.book_id AS VARCHAR2(64)) AS "bookId" RETURNING CONTENT
         ) AS invt_data
    FROM
      entity e
    WHERE e.title_txt = 'Finite Variable Analysis' OR e.subj_txt = 'Finite Mathematics';
    However, if I try this, it works at all.
    SELECT 
        e.book_id,
        
        e.title_txt,
        e.subj_txt,
        
        e.target_mkt,
        e.target_lcl_mkt,
        
        e.catg,
        e.lang_code,
        e.out_of_stock_reas,
        
        e.sucsr_title,
        e.sucsr_sub_txt,
        
        e.orig_copy_ref,
        e.orig_subj_txt,
        
        XMLQuery(
        'declare namespace invtdata="http://www.mrbook.com/InventoryData";
        
         copy $invtData := $orig/invtdata:inventory
         
         modify
         (
           for $bkRow in fn:collection("oradb:/BOOKSCHEMA/BOOK_FRAG")
           let $bk := $mpfRow/ROW/BOOK_DATA/node()
           where $bkRow/ROW/ID=$bookId
           return insert node $bk into $invtData
         ) return $invtData'
         PASSING XmlType('<inventory xmlns="http://www.mrbook.com/InventoryData" />') AS "orig",
         e.id AS "bookId" RETURNING CONTENT
         ) AS invt_data
    FROM
      entity e
    WHERE e.title_txt = 'Finite Variable Analysis' OR e.subj_txt = 'Finite Mathematics';
    The error I get with this query is:
    ORA-00932: inconsistent datatypes: expected - got BINARY
    00932. 00000 -  "inconsistent datatypes: expected %s got %s"
    *Cause:    
    *Action:
    Error at Line: 52 Column: 5
    Is it possible to leave the XQuery to use the RAW data type (16) without casting?

    KnightOfBlueArmor wrote:
    Is it possible to leave the XQuery to use the RAW data type (16) without casting?

    You are overloading the things, no need to XQuery Update in this case.
    As far as I understand it, all you need is XMLAgg:

    SELECT e.book_id
         , e.title_txt
         , e.subj_txt
         , XMLElement("inventory"
           , XMLAttributes('http://www.mrbook.com/InventoryData' as "xmlns")
           , XMLAgg( b.book_data )
           ) as inv_data
    FROM entity e
         LEFT OUTER JOIN book_frag b
                      ON b.book_id = e.book_id
    WHERE e.title_txt = 'Finite Variable Analysis'
       OR e.subj_txt = 'Finite Mathematics'
    GROUP BY e.book_id
           , e.title_txt
           , e.subj_txt
    ;
    

    (the OUTER JOIN may or may not be necessary, depending on the relationship between the two tables)

    Published by: odie_63 on March 27, 2013 23:16

Maybe you are looking for

  • Cannot upgrade iPhone iOS 9.2.1

    I tried to update my iPhone 5 iOS 9.2.1 for the last two weeks (I'm running on 8.2). Whenever I plug my phone into my computer and click on update in iTunes, I get the same message saying: "the iTunes software (11.4) is up to date" and does not updat

  • What does SOS only

    Can someone tell me when I turn on my phone, in the upper left corner that do SOS means only

  • How can I remove a reference to a file in the registry?

    When I boot I get a box telling me to remove a reference to the START. EXE from the registry.

  • Thunderbird can store not usernames, as g is added on behalf of the user.

    Thunderbird change username when I keep the name and the password. He put a g in front of the e-mail name. If e-mail was called day@this, when I use it then, it was changed to gday@this. Tree@this should be replaced with gtree@this. makes it really d

  • String.format unrecognized in the BlackBerry project?

    I'm trying to fill a string but String.format (string, string) is not recognized: "The format of the method (String, String) is not defined for the String type. Although I use jdk 1.6 and I noticed that, if I open a regular java project this recogniz