XMLAGG problem

I have query update "XMLTYPE.

but when I execute this statement my value does not get updates.


This XML query return value: '0_1000000000000000000 ~ 1024 ~. 00017578125 ~ 0 ~ 0'


Update (select res_14

of temp_records_tap_amit t

where t.call_type = 5

and t.first_record = 1

and t.res_14 is null

and t.plcode is not null

and in t.plcode select (separate plan_code

of multitier_tadig_list_amit

where trunc (t.call_date) between trunc (start_date) and trunc (end_date))

) tt

                     set (res_14) = (select rtrim (xmlagg (xmlelement (e, r_rateplan.tier_start |)))) » _'|| r_rateplan.tier_end: ' ~' | r_rateplan. Pulse: ' ~' | r_rateplan.rate |

'~'|| r_rateplan.setup_fees: ' ~' | r_rateplan.min_charge | (') .extract('//text () '),': ') as rate_values

from (select mrp.*

of m_rateplan mrp

order of mrp.tier_start

) r_rateplan

where plcode = ' 1.3'.

and call_type = 4

and callzone_calling = ' *'

and callzone_called = ' *'

); -'0_1000000000000000000 ~ 1024 ~. 00017578125 ~ 0 ~ 0'


pls help is there a property defined in oracle for XMLAGG type? or something else?

Please check the question as answered, if you are satisfied.

Tags: Database

Similar Questions

  • problem in the conversion of lines to a column

    I use Oracle 10 g on Linux. I'm trying to concatenate the rows returned by the query. Since there are more than 50 lines to concatenate, therefore, I used the getClobVal() function. There are two problems with this release:


    1. < E > at the beginning and end of the output.
    2. Double quotation marks is replaced by & quote;


    WITH T AS (
    SELECT '{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"}' json_objects   FROM dual
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"}' json_objects   FROM dual                           
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"}' json_objects   FROM dual                                  
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"}' json_objects   FROM dual                                 
    UNION
    SELECT '{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"}' json_objects   FROM dual                                     
    )
    SELECT  rtrim (xmlagg (XMLELEMENT (E, json_objects || ',')).getClobVal()) json
    FROM T
    
    
    
    JSON                                                                            
    --------------------------------------------------------------------------------
    <E>{&quot;startDate&quot;:&quot;01-JAN-2013&quot;,&quot;processName&quot;:&quot;
    CIL_FXH_PURGE_PROCESS&quot;},</E><E>{&quot;startDate&quot;:&quot;01-JAN-2999&quo
    t;,&quot;processName&quot;:&quot;CONTRACT_SYNCHRONIZATION_PROCESS&quot;},</E><E>
    {&quot;startDate&quot;:&quot;01-JAN-2999&quot;,&quot;processName&quot;:&quot;MAI
    NTAIN_CASHPOOL_PROCESS&quot;},</E><E>{&quot;startDate&quot;:&quot;01-JAN-2999&qu
    ot;,&quot;processName&quot;:&quot;MTI_PEAK_BALANCE_PROCESS&quot;},</E><E>{&quot;
    startDate&quot;:&quot;01-JAN-2999&quot;,&quot;processName&quot;:&quot;RUNNING_BA
    LANCE_PROCESS&quot;},</E>                                                       
                                                                                    
    1 row selected.
    

    Elya wrote:

    REPLACE converts CLOB VARCHAR2. The maximum size that could be 4000.

    The output generated when it is applied to the actual data consists of 8897 characters. Replace function worked correctly.

    True Yes sorry for my previous comment. I was wrong. REPLACE manages the CLOB. But this isn't the solution to your problem. You want to prevent the encoding of a certain nature while converting to XML. Using REPLACE you simply manage quotes, what other characters too can get encoded. For this you can do it like that.

    SQL> with t as  2  (  3  SELECT '{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"}' json_objects   FROM dual  4  UNION  5  SELECT '{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"}' json_objects   FROM dual  6  UNION  7  SELECT '{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"}' json_objects   FROM dual  8  UNION  9  SELECT '{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"}' json_objects   FROM dual 10  UNION 11  SELECT '{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"}' json_objects   FROM dual 12  ) 13  select dbms_xmlgen.convert 14         ( 15             xmlagg 16             ( 17                 xmlelement(A, json_objects || ',') 18             ).extract('A/text()').getclobval() 19           , 1 20         ) str 21    from t;
    
    STR--------------------------------------------------------------------------------{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"},{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"},{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"},{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"},{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"},
    
    SQL>
    
  • PROBLEM WITH XMLGEN

    Hello! I work with xml in PL/SQL files and I have the following problem:

    I want to generate the XML file, but on the output that I get the following:

    <? XML version = "1.0"? > <-ONCE

    < MIDDLE >

    < END_OF_MONTH >

    < NUMBER > 970 < / COUNT >

    < / END_OF_MONTH >

    < / AVERAGE >

    <? XML version = "1.0"? > <-SECOND TIME

    < MIDDLE >

    < BEGG_OF_MONTH >

    < NUMBER > 933 < / COUNT >

    < / BEGG_OF_MONTH >

    < / AVERAGE >

    I want to receive the only one xml version tag. You have any ideas? This is my code:

    SET SERVEROUTPUT ON

    DECLARE

    CTX DBMS_XMLGEN.ctxHandle;

    xml_file CLOB.

    number of organisation_id: = 321;

    BEGIN

    CTX: = dbms_XMLGEN.newcontext)

    q'[select sum (1) COUNTY]

    PAP per_all_people_f, asg per_all_assignments_f hr_soft_coding_keyflex hsc

    where 1 = 1

    and asg.organization_id =]' | organisation_id | q']

    and "2013-06-30' between asg.effective_start_date and asg.effective_end_date

    and "2013-06-30' between pap.effective_start_date and pap.effective_end_date

    and pap.person_id = asg.person_id

    and asg.assignment_status_type_id = 1

    and asg.payroll_id is not null

    and hsc.soft_coding_keyflex_id = asg.soft_coding_keyflex_id

    ([and not in hsc.segment4 (select lookup_code in the hl hr_lookups where hl.lookup_code in ('C01","C02") and hl.lookup_type ="PL_CONTRACT_TYPE_CIVIL")]');

    DBMS_XMLGEN.setRowSetTag (ctx, "AVERAGE");

    DBMS_XMLGEN.setRowTag (ctx, 'END_OF_MONTH');

    xml_file: = DBMS_XMLGEN.getXML (ctx);

    CTX: = dbms_XMLGEN.newcontext)

    q'[select sum (1) COUNTY]

    PAP per_all_people_f, asg per_all_assignments_f hr_soft_coding_keyflex hsc

    where 1 = 1

    and asg.organization_id =]' | organisation_id | q']

    and "2013-06-01' between asg.effective_start_date and asg.effective_end_date

    and "2013-06-01' between pap.effective_start_date and pap.effective_end_date

    and pap.person_id = asg.person_id

    and asg.assignment_status_type_id = 1

    and asg.payroll_id is not null

    and hsc.soft_coding_keyflex_id = asg.soft_coding_keyflex_id

    ([and not in hsc.segment4 (select lookup_code in the hl hr_lookups where hl.lookup_code in ('C01","C02") and hl.lookup_type ="PL_CONTRACT_TYPE_CIVIL")]');

    DBMS_XMLGEN.setRowSetTag (ctx, "AVERAGE");

    DBMS_XMLGEN.setRowTag (ctx, 'BEGG_OF_MONTH');

    xml_file: = (xml_file |) DBMS_XMLGEN. GetXml (ctx));

    dbms_output.put_line (xml_file);

    END;

    Well, to give you an idea, you have not explained how users provide month ranges, or provided us with the data, we can use...

    SQL > ed
    A written file afiedt.buf

    1 with t as (select date "'2013-06-27 as eff_start_date, date '' 2013-07-13 as eff_end_date of all the double union")
    2. Select the dates "2013-05-01', date ' 2013-08-01 Union double all the"
    3. Select the dates "2013-05-15', date ' 2013-06-07 the Union double all the"
    4. Select the dates "2013-05-15', date ' 2013-05-16 the Union double all the"
    5 select date "2013-06-01,' date ' 2013-06-01 Union double all the"
    6. Select the dates "2013-06-01', date ' 2013-06-30 the Union double all the"
    7 select date "(2013-05-01', date ' 2013-07-01' dele de double)"
    8  --
    9. end of test data
    10-
    11-
    12 - user provided, need months, provided as a start and end date
    13-
    14, user_months as (select date "2013-06-01' as start_month, date '' 2013-07-01 as the double end_month")
    15-
    16. Select ('ROOT', () xmlagg xmlelement
    17 xmlelement (xmlattributes (to_char(mnth,'YYYY-MM') 'MEDIUM', 'Month'),
    18 xmlelement ("END_OF_MONTH", xmlattributes (cnt_end as 'COUNT'))


    19, xmlelement ("BEGG_OF_MONTH", xmlattributes (cnt_start as 'COUNT'))
    20          )
    (21)) in xml format
    22 of)
    23 select add_months (start_month, l) as mnth
    24, count (case when last_day (add_months (start_month, l)) between eff_start_date and eff_end_date, then 1 other null end) as cnt_end
    25, count (case when add_months (start_month, l) between eff_start_date and eff_end_date, then 1 other null end) as cnt_start
    26 t
    27 user_months cross join
    28 cross join (select level 1 l
    29 of user_months
    30 connect by level<=>
    31                        )
    Group 32 by add_months (start_month l)
    33*      )
    SQL > /.

    XML
    ----------------------------------------------------------------

     
       
       
     

     
       
       
     

    (note: my formatting XML data)

    I have included the data as attributes rather than other nested items as your example of output seems to contain a lot of nesting redundant, just to put the data in other elements, etc..  Of course, you can flatten or nest them as much as you like, and the foregoing gives you just an example.

    I gave the example query takes a "start date" and "end date" as the range of the month the user wishes to (just provide the 1st day of each month required) and the query, and then uses techniques of the generation of line (connection by clause) in order to perform the count date for each month between the beginning and the end , using the last_day function to determine the last day of each month.

    I assumed that you'd be better to have the month in the XML provided in year and month, rather than just the name of the month, otherwise you lose potentially important information.

  • Performance of the queries XMLAGG degrading in an exponential way.

    There is a serious performance problem with my query using XMLAGG

    CREATE TABLE tmp_test_xml

    (

    acc_ID NUMBER (12).

    CLOB CUS_DTLS

    )

    INSERT INTO tmp_test_xml

    SELECT tab.acc_id acc_id

    XMLSERIALIZE (DOCUMENT XMLELEMENT ("holders"

    XMLAGG (XMLELEMENT ("holder"

    XMLELEMENT ("Gender", tab.sex_cde)

    XMLELEMENT ("Name", tab.name)

    XMLFOREST (tab.drivers_licence AS "DL")

    XMLFOREST (tab.empr_name LIKE "emp_name")

    XMLELEMENT ("Address", tab.addr)

    ..

    ...

    ...

    () ))) AS cus_dtls

    ON the TABLE tab

    Tab.acc_id group

    table 'TABLE' has 3 million records

    The Insert performance degrades as follows:

    INSERT

    10K REB - 1 s

    30K REB - 45 dry

    50K REB - 3 mins

    100K REB - 16 mins

    Please let me know if I can improve performance in some way. I can imagine how I can insert records 3 million in here...

    There is no problem of table space. Tried the 1 million without XMLAGG CER - 2 minutes.

    Y at - it another way to aggregate my xml data. In fact, I'm trying to aggregate the data for all customers for a single account.

    Version information:

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

    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

    Bravo!

    Sofiane

    Why do you think the problem is with XMLAgg?

    Try with the following definition of the table

    CREATE TABLE tmp_test_xml
    (
      acc_ID     NUMBER(12),
      CUS_DTLS  XMLTYPE -- changed storage. Defaults to SECUREFILE BINARY XML in your version
    )
    

    and also remove the XMLSERIALIZE of your SQL statement as well.

    So the performance degradation that show you reads like a memory leak, just testing to see if it is in the conversion of an XMLType to a CLOB.  You can also open an SR with Oracle's Support on the issue as well as they would have been better.

  • Problem with SQL aggregation

    I tried several different ways to do it and can't seem to find the right way to do it. We're on 10.2, so not listagg. I have the following information:

    fld_a fld_b fld_c fld_d
    12 10 1 it is
    12-10-2 a test
    14 5 1 second
    14 5 2 test

    I want to have the following result:

    12: 10, it is a test (essentially fld_a, fld_b and fld_d, ordered by fld_c)
    14, 5, second test (the fld_d on a line)

    I'm not listagg, so I tried follows him (and combos of what follows).

    Select fld_a, fld_b, fld_c,
    RTrim (xmlagg (xmlelement (e, fld_d |))) ') .extract ('/ / text()'), ',') 'fld_d '.
    of schemaname.tablename
    Group of fld_a, fld_b, fld_c

    and is not the fld_d of fld_a & fld_b group and ordered by fld_c.

    Any ideas?

    Thank you

    Victoria

    user3804901 wrote:
    I tried several different ways to do it and can't seem to find the right way to do it. We're on 10.2, so not listagg. I have the following information:

    fld_a fld_b fld_c fld_d
    12 10 1 it is
    12-10-2 a test
    14 5 1 second
    14 5 2 test

    I want to have the following result:

    12: 10, it is a test (essentially fld_a, fld_b and fld_d, ordered by fld_c)
    14, 5, second test (the fld_d on a line)

    Your problem is that your output requires no regrouping by FIELD_C - but in your query, you are group by FIELD_C

    Him below will work...

    with t (fld_a,fld_b,fld_c,fld_d) as
    (
    select 12, 10, 1,'this is' from dual union all
    select 12, 10, 2,'a test' from dual union all
    select 14, 5, 1,'second' from dual union all
    select 14, 5, 2,'test' from dual
    )
    select fld_a, fld_b,
            rtrim(
                xmlagg(
                    xmlelement (e, fld_d || ' ') order by fld_c
                      ).extract ('//text()')
                 ) "fld_d"
    from t
    group by fld_a, fld_b
    
    FLD_A FLD_B fld_d
    ----------------------------
       12    10 this is a test
       14     5 second test  
    

    Or sys_connect_by_path as already suggested

    with t (fld_a,fld_b,fld_c,fld_d) as
    (
    select 12, 10, 1,'this is' from dual union all
    select 12, 10, 2,'a test' from dual union all
    select 14, 5, 1,'second' from dual union all
    select 14, 5, 2,'test' from dual
    )
    select rtrim(replace(max(sys_connect_by_path(fld_d,'~')),'~',' ')) fld_d
    from t
    start with fld_c = 1
    connect by prior fld_a=fld_a
     and prior fld_b=fld_b
     and prior fld_c = fld_c-1
    group by fld_a,fld_b ;
    

    Published by: JAC on February 12, 2013 09:50

  • Variable printing problem Clob into 32 KB chunks using a loop

    Hello
    I tried to generate and return a XML file that is extended to the APEX with oracle 11g Express Edition 4.1 (more than 900 lines and for each line must sees 34 columns of information), but I do not know what is happening with the loop I use because only when I use a filter for consultation 19 ranks the xml file is generated, but if I need to generate the XML for all the lines (more than 900) the XML is empty and didn't display an error message.

    Please I need your help.
    Thank you.

    Attached to the code source processed:

    declare
    l_clob_XML CLOB.
    xml_size pls_integer: = 32000;
    Start
    sys. HTP.init;
    wwv_flow.g_page_text_generated: = true;
    wwv_flow.g_unrecoverable_error: = true;

    DBMS_LOB. CREATETEMPORARY (lob_loc = > l_clob_XML, cache = > false, hard = > dbms_lob.session);

    Select xmlElement
    (
    "iva"
    xmlElement ("numeroRuc", J.RUC),
    xmlElement ("razonSocial", J.RAZON_SOCIAL),
    ...
    xmlElement)
    "shopping")
    Select xmlAgg)
    xmlElement)
    "detalleCompra,"
    xmlForest)
    K.COD_SUSTENTO as "codSustento."
    K.TPLD_PROV as "tpldProv."
    ....
    )
    )
    )
    )
    SRI_COMPRAS k
    ...
    )
    )
    ). getClobVal()
    in l_clob_XML
    ANEXO_INFORMANTE j
    ....
    sys.owa_util.mime_header('Text/XML',false);
    sys. HTP.p ('Cache-Control: non-cache');
    sys. HTP.p ('Pragma: non-cache');
    sys.owa_util.http_header_close;

    Recorre - intervalos 32 k
    for i from 0... CEIL ((DBMS_LOB. GetLength (l_clob_XML) - 1) / xml_size)
    loop
    sys. HTP. PRN (dbms_lob.substr (l_clob_XML, xml_size, 1 + i * xml_size));
    end loop;

    DBMS_LOB. FREETEMPORARY (lob_loc = > l_clob_XML);
    end;

    OK, I have reproduced the issue.

    The problem is that DBMS_LOB. SUBSTR does not necessarily return the amount specified as input.
    It's a documented behaviour to account for fixed length character sets not.

    The solution is to check the length of the extracted substring to calculate the next offset.

    Here is an example of code tested successfully with a query on object, in order to obtain a large enough output XML doc:

    declare
    
      v_clob        clob;
      v_buffer      varchar2(32767);
      v_length      number;
      v_amount      number := 32767;
      v_offset      number := 1;
    
    begin
    
      sys.htp.init;
      wwv_flow.g_page_text_generated := true;
      wwv_flow.g_unrecoverable_error := true;
    
      dbms_lob.createtemporary(lob_loc => v_clob, cache => false, dur => dbms_lob.session);
    
      select xmlserialize(document
               xmlelement("rowset",
                 xmlagg(
                   xmlelement("row",
                     xmlforest(owner, object_name, subobject_name, object_id,
                               data_object_id, object_type, created, last_ddl_time,
                               timestamp, status, temporary, generated,
                               secondary, namespace, edition_name
                               )
                   )
                 )
               ) as clob
             )
      into v_clob
      from all_objects;
    
      v_length := dbms_lob.getlength(v_clob);
    
      sys.owa_util.mime_header('text/xml', false);
      sys.htp.p('Content-Length: ' || v_length);
      sys.owa_util.http_header_close;
    
      -- read and write in chunk of 32k
      while v_offset <= v_length loop
        dbms_lob.read(v_clob, v_amount, v_offset, v_buffer);
        htp.prn(v_buffer);
        v_offset := v_offset + v_amount;
      end loop;
    
      dbms_lob.freetemporary(lob_loc => v_clob);
    
    end;
    
  • Generation XML problem in APEX ORA-06502

    Hi, I have a problem with the generation of XML, I developed an application in the APEX, and in an html page, I have this process: +.

    declare
    l_XML varchar2 (32767).
    Start
    .......
    Select xmlElement
    (
    "iva"
    xmlElement ("numeroRuc", J.RUC),
    xmlElement ("razonSocial", J.RAZON_SOCIAL),
    xmlElement ("idRepre", J.ID_REPRE),
    xmlElement ("rucContador", J.RUC_CONTADOR),
    xmlElement ("anio", J.ANIO),
    xmlElement ("my", J.MES),

    xmlElement
    (
    "shopping."
    (
    Select xmlAgg
    (
    xmlElement
    (
    "detalleCompra,"
    -xmlAttributes (K.ID_COMPRA like "COMPRA"),
    xmlForest
    (
    K.COD_SUSTENTO as "codSustento."
    K.TPLD_PROV as "tpldProv."
    K.ID_PROV as "idProv."
    K.TIPO_COMPROBANTE as "tipoComprobante."
    TO_CHAR (K.FECHA_REGISTRO, ' DD/MM/YYYY "") as "fechaRegistro."
    K.ESTABLECIMIENTO as "food."
    K.PUNTO_EMISION as "puntoEmision."
    K.SECUENCIAL as "secuencial".
    TO_CHAR (K.FECHA_EMISION, ' DD/MM/YYYY "") as "fechaEmision."
    K.AUTORIZACION as 'autorizacion. "
    TO_CHAR (K.BASE_NO_GRA_IVA, 9999999999.99) as "baseNoGraIva."
    TO_CHAR (K.BASE_IMPONIBLE, 9999999999.99) as "baseImponible."
    TO_CHAR (K.BASE_IMP_GRAV, 9999999999.99) as "baseImpGrav."
    TO_CHAR (K.MONTO_ICE, 9999999999.99) as "montoIce."
    TO_CHAR (K.MONTO_IVA, 9999999999.99) as "montoIva."
    TO_CHAR (K.VALOR_RET_BIENES, 9999999999.99) as "valorRetBienes."
    TO_CHAR (K.VALOR_RET_SERVICIOS, 9999999999.99) as "valorRetServicios."
    TO_CHAR (K.VALOR_RET_SERV_100, 9999999999.99) as 'valorRetServ100 '.
    ),
    xmlElement
    (
    'air ',.
    (
    Select xmlAgg
    (
    xmlElement
    (
    "detalleAir,"
    xmlForest
    (
    P.COD_RET_AIR as "codRetAir."
    TO_CHAR (P.BASE_IMP_AIR, 9999999999.99) as "baseImpAir."
    TO_CHAR (P.PORCENTAJE_AIR, 999.99) as "porcentajeAir."
    TO_CHAR (P.VAL_RET_AIR, 9999999999.99) as 'valRetAir '.
    )
    )
    )
    ANEXO_COMPRAS p
    where P.ID_COMPRA = K.ID_COMPRA
    AND P.ID_INFORMANTE_XML = K.ID_INFORMANTE_XML
    )
    ),
    xmlElement ("estabRetencion1", K.ESTAB_RETENCION_1),
    xmlElement ("ptoEmiRetencion1", K.PTO_EMI_RETENCION_1),
    xmlElement ("secRetencion1", K.SEC_RETENCION_1),
    xmlElement ("autRetencion1", K.AUT_RETENCION_1),
    xmlElement ("fechaEmiRet1", to_char(K.FECHA_EMI_RET_1,'DD/MM/YYYY'));
    xmlElement ("docModificado", K.DOC_MODIFICADO),
    xmlElement ("estabModificado", K.ESTAB_MODIFICADO),
    xmlElement ("ptoEmiModificado", K.PTO_EMI_MODIFICADO),
    xmlElement ("secModificado", K.SEC_MODIFICADO),
    xmlElement ("autModificado", K.AUT_MODIFICADO)
    )
    )
    SRI_COMPRAS k
    WHERE K.ID IS NOT NULL
    AND K.ID_INFORMANTE_XML = J.ID_INFORMANTE
    AND K.ID BETWEEN 1 AND 25
    )
    )
    ). getClobVal()
    in l_XML
    ANEXO_INFORMANTE j
    where J.ID_INFORMANTE =: P3_MES
    and J.RUC =: P3_ID_RUC
    and J.ANIO =: P3_ANIO
    and J.MES =: P3_MES;

    -HTML
    sys.owa_util.mime_header('Text/XML',false);
    sys. HTP.p ("Content-Length: ' |") length (l_XML));
    sys.owa_util.http_header_close;
    sys. HTP. Print (l_XML);
    end;



    Now my table contains over 900 lines and only when I specifically chose 25 rows of the table "ANEXO_COMPRAS" in the case (AND K.ID BETWEEN 1 AND 25) the generated XML.

    I think the problem may be with the data type that is declared 'varchar2', but I tried with "CLOB" data type, and the error is the same. +

    declare
    l_XML CLOB.
    Start
    -View XML
    sys. HTP.init;
    wwv_flow.g_page_text_generated: = true;
    wwv_flow.g_unrecoverable_error: = true;

    -Select XML
    Select xmlElement
    ( .......

    )
    SRI_COMPRAS k
    WHERE K.ID IS NOT NULL
    AND K.ID_INFORMANTE_XML = J.ID_INFORMANTE
    .........
    ). getClobVal()
    in l_XML
    ANEXO_INFORMANTE j
    where J.ID_INFORMANTE =: P3_MES
    and J.RUC =: P3_ID_RUC
    and J.ANIO =: P3_ANIO
    and J.MES =: P3_MES;

    -HTML
    sys.owa_util.mime_header('Text/XML',false);
    sys. HTP.p ("Content-Length: ' |") length (l_XML));
    sys.owa_util.http_header_close;
    sys. HTP. Print (l_XML);
    end;

    The error generated is ORA-06502: PL/SQL: digital error or value+ _

    Please I need your help. I don't know how to solve this problem, how to use the 'CLOB' data type to the XML file can be generating+.

    Published by: JohannaCevallos07 on 26-sep-2012 10:52

    In the DECLARE section:

    l_xml       clob;
    chunk_size  pls_integer := 32767;
    

    then replace

    htp.print(l_XML);
    

    with the loop:

    for i in 0..trunc((dbms_lob.getlength(l_xml) - 1) / chunk_size)
    loop
      htp.prn( dbms_lob.substr(l_xml, chunk_size, 1 + i*chunk_size) );
    end loop;
    
  • groups nested without group xmlagg function

    I make groups nested without group xmlagg function when using the xmlagg inside another function xmlagg function. Find the structure and sample data in the table here.
     CREATE TABLE "TEST_TABLE" 
       ("KEY" NUMBER(20,0), 
        "NAME" VARCHAR2(50 ), 
        "DESCRIPTION" VARCHAR2(100 )
       );
    
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (1,'sam','desc1');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (2,'max','desc2');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (3,'peter',null);
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (4,'andrew',null);
    
    select 
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"           
               , xmlforest(Key as "ID")           
               , xmlforest(name as "ename")
               , xmlelement("Descriptions",  
               xmlagg(
                  xmlforest(description as "Desc")
                  )
                )
               )
              )
           ) as clob indent
           ) as t    
          from test_table;
    Then I removed the of the select query above and utilisΘ xmlelement xmlagg function
      select 
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"           
               , xmlforest(Key as "ID")           
               , xmlforest(name as "ename")
               , xmlelement("Descriptions",             
                  xmlforest(description as "Desc")
                  )           
               )
              )
           ) as clob indent
           ) as t    
          from test_table;
    It works fine, but the created xml with empty elements for Descriptions key 3 and 4 that has null values. I need no need descriptions element in the xml file when it is set to null. Please help me solve this problem.

    Expected behavior, it is not a bug.

    The real question is why did you put XMLAgg in the first place?
    You can expect several DESCRIPTION by employee?

    If yes then please provide some examples of data to this situation.
    If not then a simple case statement should be enough:

    SQL> set long 1000
    SQL>
    SQL> select XMLSerialize(document
      2          xmlelement("root",
      3           xmlagg(
      4             xmlelement("emp"
      5             , xmlforest(Key as "ID")
      6             , xmlforest(name as "ename")
      7             , case when description is not null then
      8                xmlelement("Descriptions",
      9                  xmlforest(description as "Desc")
     10                )
     11               end
     12             )
     13           )
     14          ) as clob indent
     15         ) as t
     16  from test_table;
    
    T
    --------------------------------------------------------------------------------
    
      
        1
        sam
        
          desc1
        
      
      
        2
        max
        
          desc2
        
      
      
        3
        peter
      
      
        4
        andrew
      
    
     
    
  • Script to generate XML files... problem with null values

    Hello everyone,

    I come here with a question that troubled me for some time. I have a script which I run in SQLPLUS every now and then to generate an XML file.

    Problem is that the data that must be in XML format are not allways <>NULL and I need to hide empty tags < / tag >.

    I'll post my script below and if you could help me with it, it would be really great!

    Thanks for reading!
    set long 20000000
    set long 20000000
    set linesize 32000
    SET ECHO OFF
    SET TRIMSPOOL on
    SET HEADING OFF
    SET PAGESIZE 50000
    SET VERIFY OFF
    SET FEEDBACK OFF
    SET TERMOUT OFF
    spool C:\test.xml
    set serveroutput on
    begin
      dbms_output.put_line('<?xml version="1.0" encoding="utf-8" ?>');
    end;
    /
    SELECT
    XMLELEMENT("ReportRoot",XMLATTRIBUTES('http://www.w3.org/2001/XMLSchema-instance' as "xmlns:xsi", 'http://www.w3.org/2001/XMLSchema' as "xmlns:xsd" , '1.0' as "Version",sysdate as "CreationDate",to_char(sysdate,'hh:mm:ss') as "CreationTime",'1524544845' as "id"),
    XMLELEMENT("Porocila",XMLELEMENT("JOLY",(SELECT XMLAGG (XMLELEMENT("RefNrReport",replace('SON'||to_char(ref_ST,'00000'),' ',''))) from access_table_2 where ref_ST = &1),
    XMLELEMENT("ReportDate",sysdate),XMLELEMENT("Labeling",'545254450'),
     (SELECT XMLAGG     (XMLELEMENT("Reportf",
                                                                     XMLELEMENT("access",access),
                                                                     XMLELEMENT("date",date),
                                                                     XMLELEMENT("datep",datep),
                                                                     XMLELEMENT("ModificationInfo",'M'),XMLELEMENT("ModificationReason",modireason)))
                                                 from v_xml_test where id_dok = &1 and ind_print = '1'))))
      .extract('/*')
      from dual
         /     
         spool off
    /
    exit
    Now lets pretend that
    XMLELEMENT("datep",datep),
    sometimes is NULL and I don't want to see it.

    Now lets pretend that

    XMLELEMENT("datep",datep),
    

    sometimes is NULL and I don't want to see it.

    XMLForest that does exactly:

    XMLForest(datep as "datep")
    

    (internally, it is equivalent to what Alex has suggested)

  • ORA-00907: lack the right parenthesis when using Group by clause with xmlagg

    I have the following query and I am getting ORA-00907 error when I use the clause with the xmlagg function group.
    select xmlelement("Mitigation",
                    xmlelement("m_szMethodName",tm.DisplayName),
                    xmlelement("SubstanceInterferenceProtocolList",
                                (select xmlagg(xmlelement("MitigationProtocol",
                                        xmlelement("m_szMethodName",tm.DisplayName),
                                        xmlelement("m_szInterferenceProtocolName",tmp.protocol_name),
                                        xmlelement("m_szInterferenceSubstance",tmp.intf_mtrl_prod_code),
                                        xmlelement("m_ProtocolParameters",
                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                xmlelement("m_Consumables",
                                                    xmlelement("Consumable",
                                                        xmlelement("m_szConsumId", xrl.rgnt_pack_name),
                                                        xmlelement("m_szProductCode",xrl.pack_prod_code),
                                                        xmlelement("m_nVolume",tmp.fluid_vol),
                                                        xmlelement("m_szProtocolStep",xps.protocol_step_name))),
                                                    xmlelement("m_ProtParamList",
                                                        xmlagg(
                                                        xmlelement("ParameterValues",
                                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                            xmlelement("m_Time",xpsd.parameter_ntime_value))
                                                        group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)
                    )))
                    order by tmp.ccd_test_id, tmp.intf_mtrl_prod_code, xps.protocol_step_intprotocolstep )
                    from XPR_tdef_mitigation_protocol tmp, xp_reagentlist xrl,
                    xpr_protocol_settings xps, xpr_protocol_settings_default xpsd
                    where tmp.ccd_test_id = tm.ccd_test_id
                    and tmp.ccd_test_id = xrl.ccd_test_id
                    and tmp.pack_prod_code = xrl.pack_prod_code
                    and tmp.intf_type = 1
                    and xps.protocol_name = xpsd.protocol_name
                    and xps.protocol_step_name = xpsd.protocol_step_name
                    and xps.ps_action_parameterlist = xpsd.ps_action_parameterlist
                    and xps.protocol_name =  tmp.PROTOCOL_NAME
                    )))
    from XPtoXPRTdef_defn_mapping tm
    where tm.DisplayName = 'SYPH'
    If I remove the clause xmlagg and the group by clause, the query works well and not give me the result.
    But in this code XML, the output format is incorrect for my application.

    Could someone help out here?

    Now my problem is that this unique coating is more than 32767 characters and utl_file can write 32767 bytes per line.
    Someone deal with this?

    Serialize the output as CLOB and DBMS_XSLPROCESSOR.clob2file procedure used to write to a file:

    DECLARE
      xml_output CLOB;
    BEGIN
      SELECT XMLElement("Department",
               XMLAgg(
                 XMLElement("Employee",e.job_id||' '||e.last_name)
                 ORDER BY e.last_name
               )
             ).getClobVal() AS "Dept_list"
      INTO xml_output
      FROM hr.employees e
      WHERE e.department_id = 30 OR e.department_id = 40;
    
      DBMS_XSLPROCESSOR.clob2file(xml_output, 'XML_DIR', 'test.xml');
    END;
    /
    
  • XMLAGG structure, performance need help for odd nesting in the schema

    Hello

    I have to produce XML to look like:
    <?xml version='1.0'?>
      <enterprise>
        <membership>
          <sourcedid>
            <id>PHYS_101_001_FA2007</id>
          </sourcedid>
        <!-- NOTE: absence of "members" level tag for XMLAGG! -->
        <member>
          <sourcedid>
            <id>D2LU0001</id>
          </sourcedid>
          <role roletype="Sample Role">
            <status>1</status>
          </role>
        </member>
        <member>
          <sourcedid>
            <id>D2LU0002</id>
          </sourcedid>
          <role roletype="Sample Role">
            <status>1</status>
          </role>
        </member>
      </membership>
    </enterprise>
    It would be simple if the scheme allowed for a '< member >' tag under which fit the tags < member >. But it does not this tag, or any other than those listed above.

    I have a query that does not produce this output (with the exception of the roletype attribute), but its execution is horrible; It takes about 40 minutes to return data:
    SELECT
         XMLROOT(
             XMLELEMENT("enterprise",
               XMLAGG(
                 XMLELEMENT("membership",
                   XMLFOREST( XMLELEMENT("id",cx.mapped_course_id) as "sourcedid"
                            ),
                   (SELECT XMLAGG(
                     XMLELEMENT("member",
                       XMLFOREST(XMLELEMENT("id",spriden_id) AS "sourcedid",
                                 XMLELEMENT("status",'1') AS "role"
                                 )
                           )
                          )
                      FROM enrollments_fall_sfrstca efs
                         , spriden sp
                         , gzv_tuid t
                     WHERE sp.spriden_change_ind IS NULL
                       AND sp.spriden_pidm       = t.pidm
                       AND t.tuid                = efs.user_name
                       AND efs.mapped_course_id  = cx.mapped_course_id
                       AND efs.term              = cx.semester
                  )
                    )
                   )
                  )
                , VERSION '1.0', STANDALONE NO VALUE)
      FROM courses_xt cx
    WHERE cx.semester = :term_code
    ;
    Similar queries produce classes and XML users very well without any performance problems, but these are driven out of the view of course or the sight of registrations, but not both.

    Is there another way that I can produce the nesting that I need for the scheme the provider?

    Source views are basically as follows (showing the relevant columns only):
    courses_xt:
    MAPPED_COURSE_ID       SEMEST
    ---------------------- ------
    AVFT209-13307-201210   201210
    AVFT210-13308-201210   201210
    enrollments_fall_sfrstca:
    MAPPED_COURSE_ID       USER_NAME
    ---------------------- ---------
    AVFT209-13307-201210    FULLERC8
    AVFT209-13307-201210    SHUPEK
    AVFT209-13307-201210    NOMAN
    AVFT210-13308-201210    SHUPEK
    AVFT210-13308-201210    PELLONM
    When I make the request without the XML (with subqueries as a column of the outer query), it returns the appropriate fast data (a few minutes).

    I tried various permutations of XMLFOREST, XMLELEMENT, XMLAGG but I get a syntax error, or the data is not going (e.g. repeated "< membership >" for each "< member >", or should I create a "< member >" invalid tag filter later).

    Please advise!

    Thank you
    Anita Lees

    Hi Anita,.

    Have you tried with a GROUP BY and any subquery?

    Here is an example of the use of schema SCOTT.
    I used the same names to tags and structure so that you can see the analogy:

    SELECT XMLElement("enterprise",
             XMLAgg(
               XMLElement("membership",
                 XMLElement("sourceid", xmlelement("id", d.deptno))
               , XMLAgg(
                   XMLElement("member",
                     XMLElement("sourceid",
                       XMLElement("id", e.empno)
                     )
                   , XMLElement("role",
                       XMLAttributes(e.job as "roletype")
                     , XMLElement("status", '1')
                     )
                   )
                 )
               )
             )
           )
    FROM scott.dept d
         LEFT OUTER JOIN scott.emp e ON e.deptno = d.deptno
    WHERE d.deptno IN (10,20)
    GROUP BY d.deptno
    ;
    

    What gives:

    
      
        
          10
        
        
          
            7782
          
          
            1
          
        
        
          
            7934
          
          
            1
          
        
        
          
            7839
          
          
            1
          
        
      
      
        
          20
        
        
          
            7369
          
          
            1
          
        
        
          
            7902
          
          
            1
          
        
        
          
            7566
          
          
            1
          
        
      
    
    
  • XMLAgg using in group by in OWB 11 GR 2

    Hello

    I want to use the sql xml operators to build the XML from relational data.
    I use 11 GR 2 (11.2.0.1)
    I followed this: http://blogs.oracle.com/warehousebuilder/entry/leveraging_xdb, but mapping wearing it is not included in the downloadable zip file.

    My problem is the following:
    I don't know how to use the group by part of the XMLAgg function in expression of OWB operator.

    I will explain:
    You have Tables DEPARTMENT and PERSON (examples of oracle data).
    The XML must be:
    < = 'SALES' service name >
    PU_CLERK Baida < employee > < / employee >
    Colmenares PU_CLERK < employee > < / employee >
    < / Department >

    Owb, you can join two tables and even use XMLAgg for combined, the employee fields.
    Something like:
    XMLAgg)
    XMLElement ("EMPLOYEE", employee.lastname)
    )

    And that put in an xmlnode becomes:

    XMLElement ("Department",
    XMLAgg)
    XMLElement ("EMPLOYEE", employee.lastname)
    )
    )

    However if I want to use the departname of the person, who is just a field in the Recordset adheres and putting that in an attribute of the node Department Oracle complains.
    XMLElement ("Department",
    XMLAttributes (department.name like "name"),
    XMLAgg)
    XMLElement ("EMPLOYEE", employee.lastname)
    )
    )
    This is because Oracle aggregates all records used for sourcing the constructed XML, not just things of the person.

    Normally, you must include a Select Group by some of the training to allow the use of the Department name in the attribute such as:

    Select
    XMLElement ("Department",
    XMLAttributes (department.name like "name"),
    XMLAgg)
    XMLElement ("EMPLOYEE", employee.lastname)
    )
    ) of the employee to join the Department on (department.xx = employee.xx)
    Department.name group

    That is the catch! By using the group by in an expression of the faulty operator in sql results since OWB generates incorrect sql when you use generate intermediary and apparently in the wrong place!
    Rather than appear after the xxx FROM it appears between the hook closing of xmlelement and FROM.
    (Of course that this is due to owb just paste the contents of entire expression operators between the parties)

    Someone knows how to fix this?
    I need some kind of workaround without resorting to the pl/sql, etc.
    As I said the blog display is not clear enough for me so if someone can help, please do :-)
    This problem should not be first on the surface because it seems commonplace, it's just that I'm perplexed and owb guide is incomplete at best on this point.
    I'm sorry for the loss of formatting, but the editor post on this forum is really...

    Published by: MichaelR64 on June 30, 2011 14:21

    Hi Michael

    You must use the aggregator to make group as in the example below, you can set other expressions to project the XML, as I did below...
    http://blogs.Oracle.com/warehousebuilder/resource/OWB/owb_xdb_example20110701.jpg

    Is that what you're after?
    See you soon
    David

  • Aggregation XML problem

    Hi all
    a have a problem of aggregation xml on the hierarchy of an xml document.
    Following initial position:

    XML-Structure:
    < layer 1 > (FK)
    < layer 2 > (FK)
    < layer 3 > (FK)
    < layer 4 / > (PK)
    < / Layer 3 >
    < / Layer2 >
    < / Layer1 >

    Now, I want to generate the XML from the database:

    create or replace view xml
    as
    Select XMLELEMENT ("layer1",

    (SELECT XMLAGG)
    XMLElement ("Layer2",

    (SELECT XMLAGG)
    XMLElement ("Layer 3",

    (SELECT XMLAGG)
    XMLElement ("Layer4",

    ))
    TABLENAME k1 where k1.layer3_id = k2.layer3_id)))

    TABLENAME k2 where k2.layer2_id = k3.layer2_id)))

    TABLENAME k3 where k3.layer1_id = kmp.layer1_id)))
    )))
    XML
    TableName kmp


    but I think it's the wrong way to solve the problem.
    Someone at - it a suggestion, to manage such structures of aggregation?

    Thank you in advance

    Yes, it helps.

    I don't see anything inherently wrong with your first approach.

    If necessary the table access can be optimized with indexes in _id columns (if they aren't already there), or perhaps a subquery factoring (use WITH clause).

    However, you can also try the following:

    create table sample_data as
    select 1 furniture_id, 1 room_id, 1 house_id, 1 family_id from dual union all
    select 2 furniture_id, 1 room_id, 1 house_id, 1 family_id from dual union all
    select 3 furniture_id, 1 room_id, 1 house_id, 1 family_id from dual union all
    select 4 furniture_id, 2 room_id, 1 house_id, 1 family_id from dual union all
    select 5 furniture_id, 3 room_id, 1 house_id, 1 family_id from dual union all
    select 6 furniture_id, 4 room_id, 2 house_id, 1 family_id from dual union all
    select 7 furniture_id, 5 room_id, 3 house_id, 2 family_id from dual union all
    select 8 furniture_id, 6 room_id, 3 house_id, 2 family_id from dual union all
    select 9 furniture_id, 6 room_id, 3 house_id, 2 family_id from dual union all
    select 10 furniture_id, 6 room_id, 3 house_id, 2 family_id from dual;
    
    SELECT xmlelement("Families",
             xmlagg(
               xmlelement("Family", xmlattributes(family_id as "family_id"),
                 xmlagg(house)
               )
             )
           ).getclobval() as "Doc"
    FROM (
      SELECT xmlelement("House", xmlattributes(house_id as "house_id"),
               xmlagg(room)
             ) as house,
             family_id
      FROM (
        SELECT xmlelement("Room", xmlattributes(room_id as "room_id"),
                 xmlagg(
                   xmlelement("Furniture", xmlattributes(furniture_id as "furniture_id"))
                 )
               ) as room,
               house_id,
               family_id
        FROM sample_data
        GROUP BY room_id, house_id, family_id
      )
      GROUP BY house_id, family_id
    )
    GROUP BY family_id
    ;
    

    It takes a single scan of the base table, since the groups are built by children (PK) parents, instead of parents to children in the first approach.

  • In 9i XMLAGG use to merge lines

    Hello

    I have some standard SQL that returns:
    Smith Parameter1 Value1
    Smith Parameter2 Value2
    Smith Parameter3 Value3
    Jones Parameter1 Value1
    Jones Parameter2 Value2
    I want the output to be displayed in the form:
    Smith Parameter1 Value1 Parameter2 Value2 Parameter3 Value3
    Jones Parameter1 Value1 Parameter2 Value2
    I've found that XMLAGG and XMLELEMENT functions make the case:
    SELECT e.EMPLOYEE, RTRIM(XMLAGG(XMLELEMENT(my_element, p.P_NAME||' '||v.P_VALUE||' ')).extract('//text()'), ' ')
    FROM my_employees e, my_parameters p, my_parameter_values v
    WHERE v.P_ID = p.P_ID
    AND v.EMP_ID = e.EMP_ID
    GROUP BY e.EMPLOYEE
    The only thing is, the SQL command order initially lines does not appear when they are merged in a single line, so I can get:
    Smith Parameter1 Value1 Parameter3 Value3 Parameter2 Value2
    Jones Parameter2 Value2 Parameter1 Value1
    He returned in the correct order if I run the SQL without the XMLELEMENTS/XMLAGG function, so I guess it's a question of how the XMLAGG function parses the data?

    Is that what I can do to fix this problem or is there another approach (in 9i) that I can use to get the required result?

    Thank you very much

    Bagpuss

    Published by: Bagpuss on July 22, 2010 03:36

    Published by: Bagpuss on July 22, 2010 03:39

    Bagpuss says:
    Is that what I can do to fix this problem or is there another approach (in 9i) that I can use to get the required result?

    The ORDER BY for XMLAGG clause gives you good results?

    SELECT e.EMPLOYEE, RTRIM(XMLAGG(XMLELEMENT(my_element, p.P_NAME||' '||v.P_VALUE||' ') ORDER BY p.P_NAME).extract('//text()'), ' ')
    FROM my_employees e, my_parameters p, my_parameter_values v
    WHERE v.P_ID = p.P_ID
    AND v.EMP_ID = e.EMP_ID
    GROUP BY e.EMPLOYEE
    
  • XmlAgg n first ordered only catch of the elements

    I can't find a way on Oracle to limit the number of lines that are aggregated by XmlAgg only the first n a specified order. I made a simple example that illustrates my problem which should be easy to reproduce, as follows:

    I have two tables, the INCIDENT and INCIDENT_LOG_ENTRY (there may be multiple entries for a given incident).

    I want to extract details of an incident (such as XML) and its last two log entries only.



    -Create the table of the INCIDENT and the two incidents:
    create table INCIDENT (ID NUMBER (10,0) PRIMARY KEY, INCIDENT_SUMMARY VARCHAR2 (200));

    insert into INCIDENT values (1, 'Hold up');
    insert into INCIDENT values (2, 'Car Accident');

    -Create table entries and the INCIDENT_LOG_ENTRY log for these two incidents:
    CREATE table INCIDENT_LOG_ENTRY (ID NUMBER PRIMARY KEY (10.0), INCIDENT_ID NUMBER (10.0), ENTRY_DATE_TIME DATE, ENTRY_TEXT VARCHAR2 (500));

    insert into INCIDENT_LOG_ENTRY values (1, 1, TO_DATE ('2009-01-01 08:15:11 ',' ' YYYY-MM-DD HH24:MI:SS), 'Hold up on Main Street');
    insert into INCIDENT_LOG_ENTRY values (2, 1, TO_DATE ('2009-01-01 08:17:40 ',' YYYY-MM-DD HH24:MI:SS'), "Continued in high-speed chase Suspect");
    insert into INCIDENT_LOG_ENTRY values (3, 1, TO_DATE ('2009-01-01 08:20:29 ',' ' YYYY-MM-DD HH24:MI:SS), "Suspect lost in traffic");
    insert into INCIDENT_LOG_ENTRY values (4, 1, TO_DATE ('2009-01-03 11:55:31 ',' ' YYYY-MM-DD HH24:MI:SS), "Suspect apprehended in the hospital");

    insert into INCIDENT_LOG_ENTRY values (21, 2, TO_DATE ('2009-01-01 08:29:15 ',' ' YYYY-MM-DD HH24:MI:SS), "Collision between car jumping the red light and truck");
    insert into INCIDENT_LOG_ENTRY values (22, 2, TO_DATE ('2009-01-01 08:45:53 ',' YYYY-MM-DD HH24:MI:SS'), "Driver taken to hospital");



    Here's the query (note order reports by xmlAgg according to the Oracle documentation):

    SELECT xmlAgg (xmlElement ('INCIDENT', xmlForest (i.ID, i.INCIDENT_SUMMARY),))
    xmlElement ("INCIDENT_LOG_ENTRIES",
    (SELECT xmlAgg (xmlElement ("INCIDENT_LOG_ENTRY", xmlForest (ile.ID, island. ENTRY_DATE_TIME, island. (Order ENTRY_TEXT)) of the island. ENTRY_DATE_TIME desc)
    ISLAND of INCIDENT_LOG_ENTRY
    WHERE island. INCIDENT_ID = i.ID
    AND rownum < = 2
    ))))
    SINCE the INCIDENT I where i.ID = 1


    And here is the result:

    < INCIDENT >
    < ID > 1 < /ID >
    Wear the < INCIDENT_SUMMARY > < / INCIDENT_SUMMARY >
    < INCIDENT_LOG_ENTRIES >
    < INCIDENT_LOG_ENTRY >
    < ID > 2 < /ID >
    < ENTRY_DATE_TIME > 1 January 09 < / ENTRY_DATE_TIME >
    < ENTRY_TEXT > Suspect continued in high speed pursuit < / ENTRY_TEXT >
    < / INCIDENT_LOG_ENTRY >
    < INCIDENT_LOG_ENTRY >
    < ID > 1 < /ID >
    < ENTRY_DATE_TIME > 1 January 09 < / ENTRY_DATE_TIME >
    < ENTRY_TEXT > Hold up on Main Street < / ENTRY_TEXT >
    < / INCIDENT_LOG_ENTRY >
    < / INCIDENT_LOG_ENTRIES >
    < / INCIDENT >


    This isn't the desired result - I want the last two entries in journal (4 and 3). Clearly the rownum took effect before the classification is applied by XmlAgg. However, if I try to force the order first by using a nested subquery, Oracle complained that the incident (table alias 'i') is not visible in the subquery:

    SELECT xmlAgg (xmlElement ('INCIDENT', xmlForest (i.ID, i.INCIDENT_SUMMARY),))
    xmlElement ("INCIDENT_LOG_ENTRIES",
    (SELECT xmlAgg (xmlElement ("INCIDENT_LOG_ENTRY", xmlForest (ile.ID, island. ENTRY_DATE_TIME, island. (Order ENTRY_TEXT)) of the island. ENTRY_DATE_TIME desc)
    FROM (select * from (select * from INCIDENT_LOG_ENTRY WHERE INCIDENT_ID = ENTRY_DATE_TIME order i.ID) where rownum < = 2) island
    ))))
    SINCE the INCIDENT I where i.ID = 1

    Which translates into:
    SQL error: ORA-00904: "I." "" Id ": invalid identifier



    If anyone knows how to solve this problem, I would be extremely grateful.



    (BTW, it works without any problem on SQL Server):

    Select i.ID, i.INCIDENT_SUMMARY,.
    (select the 2 best ile.ID, island. ENTRY_TEXT, island. ENTRY_DATE_TIME
    Island of INCIDENT_LOG_ENTRY
    where island. INCIDENT_ID = i.ID
    order of the island. ENTRY_DATE_TIME desc for xml path ('INCIDENT_LOG_ENTRY'), type) as "INCIDENT_LOG_ENTRIES".
    Since the INCIDENT I
    where i.ID = 1
    for xml path ('INCIDENT') type

    Which gives the desired result:

    < INCIDENT >
    < ID > 1 < /ID >
    Wear the < INCIDENT_SUMMARY > < / INCIDENT_SUMMARY >
    < INCIDENT_LOG_ENTRIES >
    < INCIDENT_LOG_ENTRY >
    < ID > 4 / < ID >
    < ENTRY_TEXT > Suspect apprehended in hospital < / ENTRY_TEXT >
    < ENTRY_DATE_TIME > 2009-01-03T 11: 55:31 < / ENTRY_DATE_TIME >
    < / INCIDENT_LOG_ENTRY >
    < INCIDENT_LOG_ENTRY >
    < ID > 3 < /ID >
    < ENTRY_TEXT > Suspect lost in traffic < / ENTRY_TEXT >
    < ENTRY_DATE_TIME > 2009 - 01-01 T 08: 20:29 < / ENTRY_DATE_TIME >
    < / INCIDENT_LOG_ENTRY >
    < / INCIDENT_LOG_ENTRIES >
    < / INCIDENT >

    )
    SQL> set lines 160
    SQL> column ENTRY_TEXT format A64
    SQL> select ile.ID, ile.ENTRY_DATE_TIME, ile.ENTRY_TEXT
      2    from INCIDENT_LOG_ENTRY ile
      3   order by ile.ENTRY_DATE_TIME desc
      4  /
             4 03-JAN-09 Suspect apprehended in hospital
            22 01-JAN-09 Driver taken to hospital
            21 01-JAN-09 Collision between car jumping red light and lorry
             3 01-JAN-09 Suspect lost in traffic
             2 01-JAN-09 Suspect pursued in high speed chase
             1 01-JAN-09 Hold up on Main Street
    
    6 rows selected.
    
    Elapsed: 00:00:00.01
    SQL> select ile.ID, ile.ENTRY_DATE_TIME, ile.ENTRY_TEXT
      2    from INCIDENT_LOG_ENTRY ile
      3   where rownum <= 2
      4   order by ile.ENTRY_DATE_TIME desc
      5  /
             2 01-JAN-09 Suspect pursued in high speed chase
             1 01-JAN-09 Hold up on Main Street
    
    Elapsed: 00:00:00.01
    SQL> select ile.ID, ile.ENTRY_DATE_TIME, ile.ENTRY_TEXT
      2    from (
      3            select ile.ID, ile.ENTRY_DATE_TIME, ile.ENTRY_TEXT
      4              from INCIDENT_LOG_ENTRY ile
      5              order by ile.ENTRY_DATE_TIME desc
      6         ) ile
      7   where rownum <= 2
      8  /
             4 03-JAN-09 Suspect apprehended in hospital
            22 01-JAN-09 Driver taken to hospital
    
    Elapsed: 00:00:00.00
    SQL> create or replace view INCIDENT_LOG_ENTRY_ORDERED
      2  as
      3  select *
      4    from INCIDENT_LOG_ENTRY
      5   order by INCIDENT_ID, ENTRY_DATE_TIME desc
      6  /
    
    View created.
    
    Elapsed: 00:00:00.15
    SQL> SELECT xmlserialize
      2         (
      3           DOCUMENT
      4           xmlAgg
      5           (
      6             xmlElement
      7             (
      8               "INCIDENT",
      9               xmlForest(i.ID, i.INCIDENT_SUMMARY),
     10               xmlElement
     11               (
     12                 "INCIDENT_LOG_ENTRIES",
     13                 (
     14                   SELECT xmlAgg
     15                          (
     16                            xmlElement
     17                            (
     18                               "INCIDENT_LOG_ENTRY",
     19                               xmlForest(ile.ID, ile.ENTRY_DATE_TIME, ile.ENTRY_TEXT)
     20                            )
     21                          )
     22                     from INCIDENT_LOG_ENTRY_ORDERED ile
     23                    WHERE ile.INCIDENT_ID = i.ID
     24                      and rownum < 3
     25                 )
     26               )
     27             )
     28           )
     29         as CLOB indent size = 2
     30         )
     31    FROM INCIDENT i
     32   where i.ID = 1
     33  /
    
      1
      Hold up
      
        
          4
          2009-01-03
          Suspect apprehended in hospital
        
        
          3
          2009-01-01
          Suspect lost in traffic
        
      
    
    
    Elapsed: 00:00:00.07
    SQL>
    

Maybe you are looking for