A better way to generate the needed XML?

I am working on a 10.2 system and looking to see if there is a better way to generate the resulting XML than what I have come up with. Here is a test case and the output it generates. I don't really like querying the table for each column needed as the real table has eight columns I am pulling. I would like to make one pass on person_h and get the info needed instead of making eight passes, but not sure if it is possible.
with person_h as
   (select 1 id, 'M' gender, 'W' race, '170' weight from dual union all
    select 1, 'M', 'W', '170' from dual union all
    select 1, 'M', 'W', '180' from dual union all
    select 1, 'M', NULL, '175' from dual union all
    select 1, NULL, 'W', NULL from dual
select xmlelement("Person",
         (select xmlagg(xmlelement("Sex", gender))
            from (select distinct gender
                    from person_h
                   where id = 1
                     and gender is not null) pg),
         (select xmlagg(xmlforest(race as "Race"))
            from (select distinct race
                    from person_h
                   where id = 1) pg),
         (select xmlagg(xmlforest(weight as "Weight"))
            from (select distinct weight
                    from person_h
                   where id = 1) pg)
       ).getstringval()
  from dual;
Output
<Person>
  <Sex>M</Sex>
  <Race>W</Race>
  <Weight>170</Weight>
  <Weight>175</Weight>
  <Weight>180</Weight>
</Person>Note: Previously posted on the XML DB forum at A better way to generate the needed XML? but still looking for other solutions so putting in front of more eyes here. I have considered using a WITH statement to do the initial query on person_h but haven't tested that yet to see what Oracle really will do as just getting back around to this lower priority task of mine.

I'm using the WITH statement to simulate a table and DUAL/UNION ALL to create data in that "table". I've seen it used plenty of times in this forum so not sure why a problem for this example. The actual SQL/XML statement hits that "base table" three times, so I didn't include all eight columns because three columns is sufficient to show the problem in the way I coded the SQL. Following the SQL is the sample OUTPUT that SQL statement generates and that is the output I created and need. I'm just looking for other options to achieve the listed output.

Similar Messages

  • How to generate the following XML-Output?

    Hi all,
    I would like to generate the following XML-Output without defining any types or tables:
    <?xml version = '1.0'?>
    <DEPARTMENTS_EMPLOYEES>
    <DEPARTMENT NAME="ACCOUNTING">
    <DEPTNO>10</DEPTNO>
    <LOC>NEW YORK</LOC>
    <EMPLOYEES_OF_DEPARTMENT>
    <EMPNO>...</EMPNO>
    <ENAME>...</ENAME>
    </EMPLOYEES_OF_DEPARTMENT>
    </DEPARTMENT>
    <DEPARTMENT NAME="RESEARCH">
    <DEPTNO>20</DEPTNO>
    <LOC>DALLAS</LOC>
    <EMPLOYEES_OF_DEPARTMENT>
    </EMPLOYEES_OF_DEPARTMENT>
    </DEPARTMENT>
    </DEPARTMENTS_EMPLOYEES>
    Unfortunately the following SQL-Statement does not working:
    select xmlElement("DEPARTMENTS_EMPLOYEES",
    xmlAttributes(d.deptno as "DEPTNO"),
    xmlElement("DNAME", d.dname),
    xmlElement("LOC", d.loc),
    xmlElement("EMPLOYEES_OF_DEPARTMENT",
    (select xmlAgg(xmlElement("EMPLOYEE", xmlAttributes(e.empno as "EMPNO"), xmlForest(e.ename as "ENAME", e.job as "JOB", e.hiredate as "HIREDATE", e.sal as "SAL", e.comm as "COMM", m.empno as "MGRNO", m.ename as "MGRNAME" ) )
    from emp e, emp m
    where e.deptno = d.deptno
    and m.empno = e.mgr
    ) as XML
    from dept d;
    1. When I provide this statement with SQL*Plus
    (unfortunately 9.0.1.3.0) then I get the
    following output:
    XML()
    XMLTYPE()
    XMLTYPE()
    XMLTYPE()
    XMLTYPE()
    2. When I provide this statement with SQL Navigator
    4.3.0.456 then I get the following error:
    [1]: (Error): OCI-21560: argument 3 is null, invalid,
    or out of range
    3. When I execute the following PL/SQL-Code then I get
    the XML-Error message:
    DECLARE
    x CLOB;
    xmlstr VARCHAR2(32767);
    line VARCHAR2(2000);
    BEGIN
    x := dbms_xmlquery.getxml('select xmlElement("DEPARTMENT",
    xmlAttributes(d.deptno as "DEPTNO"),
    xmlElement("DNAME", d.dname),
    xmlElement("LOC", d.loc),
    xmlElement("EMPLOYEELIST",
    (select xmlAgg(xmlElement("EMPLOYEE",
    xmlAttributes(e.empno as "EMPNO"),
    xmlForest(e.ename as "ENAME",
    e.job as "JOB",
    e.hiredate as "HIREDATE",
    e.sal as "SAL",
    e.comm as "COMM",
    m.empno as "MGRNO",
    m.ename as "MGRNAME"
    from emp e, emp m
    where e.deptno = d.deptno
    and m.empno = e.mgr
    ) as XML
    from dept d');
    xmlstr := dbms_lob.SUBSTR(x,32767);
    LOOP
    EXIT WHEN xmlstr IS NULL;
    line := SUBSTR(xmlstr,1,INSTR(xmlstr,CHR(10))-1);
    DBMS_OUTPUT.PUT_LINE(line);
    xmlstr := SUBSTR(xmlstr,INSTR(xmlstr,CHR(10))+1);
    END LOOP;
    END;
    <?xml version = '1.0'?>
    <ERROR>oracle.xml.sql.OracleXMLSQLException: Unimplemented Feature</ERROR>
    4. When I provide the following PL/SQL-Code then I get the same xml-error:
    DECLARE
    x CLOB;
    xmlstr VARCHAR2(32767);
    line VARCHAR2(2000);
    BEGIN
    x := dbms_xmlquery.getxml('select xmlElement("SYSDATE", xmlElement("Datum", to_char(sysdate,''DD.MM.YYYY'')),
    xmlElement("Zeit", to_char(sysdate,''HH24:MI:SS''))) as XML
    from dual');
    xmlstr := dbms_lob.SUBSTR(x,32767);
    LOOP
    EXIT WHEN xmlstr IS NULL;
    line := SUBSTR(xmlstr,1,INSTR(xmlstr,CHR(10))-1);
    DBMS_OUTPUT.PUT_LINE(line);
    xmlstr := SUBSTR(xmlstr,INSTR(xmlstr,CHR(10))+1);
    END LOOP;
    END;
    <?xml version = '1.0'?>
    <ERROR>oracle.xml.sql.OracleXMLSQLException: Unimplemented Feature</ERROR>
    Can I generate the needed XML-Output from Database with SQL or PL/SQL?
    Can anybody help me?
    Regards
    Leonid Pavlov

    I have this done with:
    DECLARE
    qryCtx DBMS_XMLGEN.ctxHandle;
    result CLOB;
    xmlstr VARCHAR2(32767);
    line VARCHAR2(2000);
    BEGIN
    qryCtx := dbms_xmlquery.newContext('select deptno, dname, loc, cursor(select e.empno, e.ename, e.job,
    to_char(e.hiredate,''DD.MM.YYYY'') hiredate, e.sal, e.comm,
    m.empno MGRNO, m.ename MGRNAME
    from emp e, emp m
    where e.deptno = dept.deptno
    and m.empno(+) = e.mgr) emp
    from dept');
    dbms_xmlquery.useNullAttributeIndicator(qryCtx, FALSE);
    dbms_xmlquery.setRowsetTag(qryCtx, 'DEPARTMENTS_EMPLOYEES');
    dbms_xmlquery.setrowtag(qryCtx, 'DEPARTMENT');
    DBMS_XMLQuery.setRowIdAttrName(qryCtx, 'ID');
    DBMS_XMLQuery.setRowIdAttrValue(qryCtx, 'DEPTNO');
    -- dbms_xmlquery.setrowidattrname(qryCtx, NULL);
    result := dbms_xmlquery.getXML(qryCtx);
    DBMS_XMLQuery.closeContext(qryCtx);
    xmlstr := dbms_lob.SUBSTR(result,32767);
    LOOP
    EXIT WHEN xmlstr IS NULL;
    line := SUBSTR(xmlstr,1,INSTR(xmlstr,CHR(10))-1);
    DBMS_OUTPUT.PUT_LINE(line);
    xmlstr := SUBSTR(xmlstr,INSTR(xmlstr,CHR(10))+1);
    END LOOP;
    END;
    But how can I rename the <EMP>-Element to Employees?

  • Simplest way to disassemble the multiple xml records to single xml record?

    Guys,
    I just want to know the what can be the simplest way to disassemble the input xml file into single records.
    Can we use built in XML disassemble component in custom pipeline to disassemble? If yes, how can we do it.
    Or what is other way to do it.

    Why you don't want to use Envelop Schema? Is there any specific reason for that?
    Creating envelope schema won't be a tough task you just need to make Envelop property of Schema to Yes and set Body Xpath to the container record for the child records you wish to process individually.
    Also you will have to create schema representing your child xml structure.
    Refer
    this article, it gives step by step description of the same.
    Also, as John suggested you don't even have to create a custom pipeline as the debatching can be done using default XML Receive pipeline itself.
    Let us know if you have any further question.
    Thanks,
    Prashant
    Please mark this post accordingly if it answers your query or is helpful.

  • Better way of deploying the ODI artifacts across Dev,UAT,Prod instances

    Hi All,
    We have a requirement wherein we have to deploy the ODI artifacts from one repository to the other across various instances.
    From what I learned from the export and import operations in ODI documents provided by Oracle, we have Internal Identifiers (IDs) for each and every export and import. And while importing the work repository, we have to delete the old one and then import the new one.Is there a way where we can use the existing identifier and just append the changes?
    Do we have any better way of deploying the ODI artifacts across Dev,UAT,Prod instances that would import the artifacts and also import the changes to the existing artifacts?
    Any kind of information related to deployement is higly appreciated.
    Thanks in advance,

    Not sure you have understood how the object identifiers work in ODI. When you migrate artifacts/objects between repositories (as long as your repository ID's are unique across the environments) you should be able to import using Synonym Insert/Update mode and this will give you desired behaviour you are looking for. The only area that really requires close attention during the process is ensuring that you import the various artifacts/objects in the correct sequence

  • Best way to generate the XML files from a DTD file

    Hey,
    I am writing an application that needs to convert a complicated data structure into an xml file. I have design a DTD file that describes the data structure.
    My question is what is the best, most efficient way to covert the data structures (objects) into the XML files with a DTD file.
    Thank you very much.
    Candy

    Convert the DTd to an XML Schema. Generate java classes from Schema with Jaxb. Create an XML document from the java classes.

  • Is there a way to get the actual XML string when using the JAXP SAX Parser?

    Hi All,
    I am using a JAXP SAX xml parser and am looking for a way to get the actual line of xml that is being parsed from within a content handler.
    Here's my scenario. Consider the following example xml document.
    <formCollection>
       <form name="myForm">
          <text/>
          <selection/>
       </form>
       <form name="anotherForm">
          <text/>
       </form>
    </formCollection>My hope is to validate the entire document and then insert an xml string containing each "form" element (and its sub-elements) into a map for later use. My thought was to create a String as each "form" element is being parsed (begining with the form's startElement event and concatenating until the form's endElement event is reached) and then inserting this string into the map. Is there a way to get the actual line of xml that is being parsed, rather than just the element name and attribute values?

    DrClap wrote:
    YouRang wrote:
    2. The first handler would validate the entire XML document, extract the "type" attribute from each <form> element, and place each <form> element and its sub-elements into the map of Strings, using the "type" attribute as the key. The second handler would take a <form> element and parse it into a Form object for the display. This option was the impetus for my question because it relies on the first handler being able to access the entire <form> element XML String and write it to a map.I don't see why you need the raw data from the XML document here. You should already be abstracting your data into Java classes in the first handler, instead of making the second handler do the parsing all over again.Correct, I am not referring to XForms. In this case, it happens that I am using the XML to generate an SWT ScrolledForm object and, thus, the XML element name happens to be named "form." However, the concept/design problem could apply to any type of object and the XML element could be appropriately renamed.
    My experience with XSLT is limited and I haven't done anything with it for several years. With that said, it seems that it is primarily used for generating web content, which wouldn't apply in this case because this is for a client-server application. I could be off base on this one -- if XSLT applies to much broader translations and would be more appropriate for generating Java objects than my current methodology, I could certainly look into it further.
    I apologize that option two didn't make more sense; it is difficult to explain. Yes, optimally the data should be abstracted into Java classes in the first handler. This is really an elaboration that I failed to specify when explaining option one. The problem is that the user can choose to create any number of "forms" of any type. For instance, let's say that from the File -> New menu there are options for seven different types of forms and each form is used to send completely different data. The user can select form1, select form1 again, select form4, and select form7 (or any other combination) and bring up tabs that display the different forms. The user can then enter data and submit each form separately. When the user selects File -> New -> FormX, a SWT ScrolledForm object that corresponds with FormX must be given to the display. Because SWT ScrolledForm objects do not allow a deep copy, I cannot simply read the XML <form> elements at initialization, parse them into ScrolledForm objects, and pass deep copies of the ScrolledForm objects to the display each time the user clicks File -> New -> FormX. The only simple way I see of getting a new copy of a ScrolledForm object is to reparse the appropriate XML <form> element in order to create one each time the user selects File -> New -> FormX. As such, one handler would need to read the entire XML document and parse the <form> elements into a map (or some other data structure) and another handler would need to parse individual <form> elements into SWT ScrolledForm objects. The first handler would be called at initialization and the second handler would be called each time a user clicked on File -> New -> FormX. Once again, this isn't exactly my favorite implementation... but seems the simplest given that there is no way to do a deep copy of an SWT ScrolledForm object. Hopefully that makes a little more sense. No worries if it doesn't -- I just figured I'd throw this out there and see if anyone had a better idea.

  • Is there a better way to generate custom timed digital Signals

    I am trying to generate digital output of high and lows with particular delays on different lines. Each daq assistant is activating single line on a port on USB 6501. There more complex high and lows that I need to generate with variable time difference between high and low. There is codebelow which accomplishes what I am trying to achieve but for executing a long pattern of high and low signal is very time consuming to do this way. I am sure there is a better way to do this, I  not a expert on labview so I haven't uncovered its full potential. Can anybody suggest a more effective and a quick way to do this. I would hgihly appreciate. Thanks!
    I have not shown in the code below but through DAQ assistant I have initialized lines to low level logic.
    Solved!
    Go to Solution.

    See the attached file
    Attachments:
    Digital Signal.vi ‏335 KB

  • Is there better way to do this?  (Xml Pretty Print | node removing)

    Hi all, I have been working at home on a small project to help my Java Jedi training. :-)
    My app saves quotes from authors in an xml file.
    I have a class [XmlRepository extends Thread] that holds control of an xml file to handle requests for Nodes.
    When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.
    Pretty print or correct Node removing.
    part of my xml is like this (I have resumed it for readability):
        <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
            <quotes/>
            <authors>
                <author id="f156c570-c676-4d69-9b15-ae7d859ff771" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Poe</lastNames>
                    <firstNames>Edgar Allan</firstNames>
                </author>
                <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Wilde</lastNames>
                    <firstNames>Oscar</firstNames>
                </author>
                <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Christie</lastNames>
                    <firstNames>Agatha</firstNames>
                </author>
                <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Shakespeare</lastNames>
                    <firstNames>William</firstNames>
                </author>
            </authors>
        </entities>If I remove A Node ( Edgar Allan Poe (1st in this case)) the resulting Xml when saved is like this (I have added the space indentation just as it is outputted by my code):
        <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
            <quotes/>
                <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Wilde</lastNames>
                    <firstNames>Oscar</firstNames>
                </author>
                <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Christie</lastNames>
                    <firstNames>Agatha</firstNames>
                </author>
                <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Shakespeare</lastNames>
                    <firstNames>William</firstNames>
                </author>
            </authors>
        </entities>this is how I initialize the XML DOM Handlers, and the method for removing a Node:
         * Initializes factory instances and member variables.
        private void initialize() {
            //obtain an instance of a documentFactory create a document documentBuilder
            this.documentFactory = DocumentBuilderFactory.newInstance();
            //Configure the documentFactory to be name-space aware and validate trough an xsd file
            this.documentFactory.setNamespaceAware(true);
            this.documentFactory.setValidating(true);
            this.documentFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            try {
                //obtain an instance of an XPathFactory
                this.xpathFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
                //obtain an instance of the xpath evaluator object
                this.xpathEvaluator = this.xpathFactory.newXPath();
                //set namespace mapping configurations
                NamespaceContextMap namespaceMappings = new NamespaceContextMap();
                namespaceMappings.put("xml", "http://www.w3.org/XML/1998/namespace");
                namespaceMappings.put("xmlns", "http://www.w3.org/2000/xmlns/");
                namespaceMappings.put("xsd", "http://www.w3.org/2001/XMLSchema");
                namespaceMappings.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                namespaceMappings.put(this.schemaNamespaceMapping, this.schemaNamespace);
                //add mappings
                this.xpathEvaluator.setNamespaceContext(namespaceMappings);
            } catch (XPathFactoryConfigurationException ex) {
                Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, ex);
            try {
                //obtain a trasformer factory to save the file
                this.transformerFactory = TransformerFactory.newInstance();
                this.transformerFactory.setAttribute("indent-number", 4);
                //obtain the transforme
                this.transformer = this.transformerFactory.newTransformer();
                //setup transformer
                this.transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                this.transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                this.transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text");
                this.transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            } catch (TransformerConfigurationException tcex) {
                Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, tcex);
         * Removes a node by evaluating the XPATH expression.
         * @param xpath A String instance with the XPATH expression representing the element to remove.
         * @throws com.fdt.cognoscere.storage.exceptions.UnableToRemoveException When an exception occurs that prevents the repository to execute the remove statement.
        public void removeNode(final String xpath) throws UnableToRemoveException {
            Node nodeToRemove = null;
            Node parentNode = null;
            //verify xpath
            if (xpath == null)
                throw new IllegalArgumentException("The xpath argument cannot be null.");
            //verify that the repository is loaded
            if (!this.loaded)
                throw new IllegalStateException("The XmlRepository faild to load properly and it is in an invalid state. It cannot perfom any operation.");
            try {
                //get the node to remove out of the xpath expression
                nodeToRemove = this.getNode(xpath);
                //throw an exception if no node was found to remove
                if (nodeToRemove == null)
                    throw new UnableToFindException("The node element trying to be remove does not exist.");
                //obtain the parent node to remove its child
                parentNode = nodeToRemove.getParentNode();
                //remove the node from the parent node
                nodeToRemove = parentNode.removeChild(nodeToRemove);
            } catch.......removed to save space{
            } finally {
                //normalize document
                this.document.normalize();
        }Please tell me if I could do this better,
    thanks,
    f(t)

    franciscodiaztrepat wrote:
    When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.Replaced? No, there's already a new-line character after the node that was removed. And there was one before that node too. You didn't remove either of those, so after the removal there are two consecutive new-line characters. As you can see.
    And no, trying to pretty-print the XML document won't remove any of those. It might add whitespace to make the document nicely indented, but it won't ever remove whitespace. If you want whitespace removed then you'll have to do it yourself.
    For example, after you remove a node, also remove the node following it if it's a whitespace text node. Or something like that.

  • Is there a way to generate the growth trend report in EM or using SQL

    Hi,
    I want to have some sort of tool to generate the growth trend of the database.
    I have tried
    col TIMEPOINT format a30
    select * from table(dbms_space.OBJECT_GROWTH_TREND ('&Schema','&TABLE_NAME','TABLE'));
    but above is only for one table and it do not show much old data like last year or how the table will look like next year or 3 months later.
    I believe Enterprise manager or Grid Control will have something to serve my purpose which I am not aware of.
    Once again my question is:
    We have databases (9, 10, 11) which are there from years and want to know that how it have grown and how it will grow in future. It will be good if we have more granularity in the tool. If there is any external tool Non Oracle then let me know as well.
    Any help is greatly appreciated.
    --Harvey.
    Edited by: Harvey on Jan 14, 2011 10:33 AM
    Edited by: Harvey on Jan 14, 2011 3:26 PM

    Hey guys .. i was researching trying to find information about some kind of growth analysis reporting tool and since i couldn't find anything that i like i created some Unix scripts that send automated reports showing growth analysis graphics. I use Chart apis from Google to generate the graphics on the client side. Check it out.
    The script will load the data in a daily basis and send the report at the end. The space needed is about 512M depending on the amount of objects and it's stored in a tablespace defined during the configuration of the process.
    http://cesalo.wordpress.com/2011/01/17/google-chart-api-and-oracle-database-growth-reports
    --Cesar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to generate the following XML

    Hi all,
    I have 2 tables, demo_orders and demo_order_items (child)
    how can I generate something like this :
    <?xml version="1.0"?>
    <ROWSET>
    <ROW>
      <ORDER_ID>1</ORDER_ID>
      <CUSTOMER_ID>1</CUSTOMER_ID>
      <ORDER_TOTAL>1200</ORDER_TOTAL>
      <ORDER_TIMESTAMP>2009-01-16T16:20:09.000</ORDER_TIMESTAMP>
      <USER_ID>2</USER_ID>
      <ITEMS>
       <ITEMROW>
        <ORDER_ITEM_ID>1</ORDER_ITEM_ID>
        <ORDER_ID>1</ORDER_ID>
        <PRODUCT_ID>1</PRODUCT_ID>
        <UNIT_PRICE>1200</UNIT_PRICE>
        <QUANTITY>1</QUANTITY>
       </ITEMROW>
      </ITEMS>
    </ROW>
    <ROW>
      <ORDER_ID>2</ORDER_ID>
      <CUSTOMER_ID>2</CUSTOMER_ID>
      <ORDER_TOTAL>599</ORDER_TOTAL>
      <ORDER_TIMESTAMP>2009-01-11T16:20:09.000</ORDER_TIMESTAMP>
      <USER_ID>2</USER_ID>
      <ITEMS>
       <ITEMROW>
        <ORDER_ITEM_ID>2</ORDER_ITEM_ID>
        <ORDER_ID>2</ORDER_ID>
        <PRODUCT_ID>2</PRODUCT_ID>
        <UNIT_PRICE>199</UNIT_PRICE>
        <QUANTITY>1</QUANTITY>
       </ITEMROW>
       <ITEMROW>
        <ORDER_ITEM_ID>3</ORDER_ITEM_ID>
        <ORDER_ID>2</ORDER_ID>
        <PRODUCT_ID>8</PRODUCT_ID>
        <UNIT_PRICE>50</UNIT_PRICE>
        <QUANTITY>2</QUANTITY>
       </ITEMROW>
      </ITEMS>
    </ROW>
    </ROWSET>

    Hi, I'm assuming that table columns have the same names as the xml elements in your example.
    Try this:
    SQL >select xmlelement("ROWSET",
      2                    xmlagg(xmlelement("ROW",xmlforest(order_id,
      3                                                      customer_id,
      4                                                      order_total,
      5                                                      to_char(order_timestamp,'yyyy-mm-dd"T"hh24:mi:ss.FF3') as "ORDER_TIMESTAMP",
      6                                                      user_id),
      7                                            xmlelement("ITEMS",(select
      8                                                               xmlagg(xmlelement("ITEMROW",xmlforest(order_item_id,
      9                                                                                                     order_id,
    10                                                                                                     product_id,
    11                                                                                                     unit_price,
    12                                                                                                     quantity)
    13                                                                                )
    14                                                                     ) from demo_order_items i where i.order_id=o.order_id)
    15                                                       )
    16                                     )
    17                          )
    18                   ).extract('/*') as yourXML
    19    from demo_orders o; 
    YOURXML
    <ROWSET>
      <ROW>
        <ORDER_ID>1</ORDER_ID>
        <CUSTOMER_ID>1</CUSTOMER_ID>
        <ORDER_TOTAL>1200</ORDER_TOTAL>
        <ORDER_TIMESTAMP>2009-12-28T10:19:01.464</ORDER_TIMESTAMP>
        <USER_ID>2</USER_ID>
        <ITEMS>
          <ITEMROW>
            <ORDER_ITEM_ID>1</ORDER_ITEM_ID>
            <ORDER_ID>1</ORDER_ID>
            <PRODUCT_ID>1</PRODUCT_ID>
            <UNIT_PRICE>1200</UNIT_PRICE>
            <QUANTITY>1</QUANTITY>
          </ITEMROW>
        </ITEMS>
      </ROW>
      <ROW>
        <ORDER_ID>2</ORDER_ID>
        <CUSTOMER_ID>2</CUSTOMER_ID>
        <ORDER_TOTAL>599</ORDER_TOTAL>
        <ORDER_TIMESTAMP>2009-12-28T10:19:01.464</ORDER_TIMESTAMP>
        <USER_ID>2</USER_ID>
        <ITEMS>
          <ITEMROW>
            <ORDER_ITEM_ID>2</ORDER_ITEM_ID>
            <ORDER_ID>2</ORDER_ID>
            <PRODUCT_ID>2</PRODUCT_ID>
            <UNIT_PRICE>199</UNIT_PRICE>
            <QUANTITY>1</QUANTITY>
          </ITEMROW>
          <ITEMROW>
            <ORDER_ITEM_ID>3</ORDER_ITEM_ID>
            <ORDER_ID>2</ORDER_ID>
            <PRODUCT_ID>8</PRODUCT_ID>
            <UNIT_PRICE>50</UNIT_PRICE>
            <QUANTITY>2</QUANTITY>
          </ITEMROW>
        </ITEMS>
      </ROW>
    </ROWSET>The extract('/*') method it's only useful to get a pretty formatted output. Remove it in your production applications for better performances and space saving.
    Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/27/inviare-email-dal-db-utilizzando-utl_smtp/]

  • A better way to determine the current state of the FLVPlayback component?

    Below is the AS3 code I have used to display images (MCs) over an instance of the FLVPlayback component.  These images (one for loading, one for the title) are to appear – or disappear – according to the current state of the FLVPlayback component. 
    It “works,” but when testing, I have noticed that it can be rather finicky.  The most common issue that arises is that many times the loadPoster movieclip will still be visible even though the video has entered the playing state.
    Also, I wanted a title placeholder image to appear whenever the user stops the video or if the video completes.  However, I had to add the conditional statement to the “stoppedStateEntered” case to make everything appear when expected.  When the video is first viewed (and has completed buffering), it seems that the FLVPlayback component enters the stopped state before entering the playing state.  Thus, the titlePoster would flash on the screen right before it and the loadPoster “should” disappear when the video begins playing.
    Even in my limited testing, these issues were very easily re-created.  I am definitely looking for a more reliable solution.  Is there a better (or more correct) way to go about all this?  If possible, I would like to stick with the FLVPlayback component, just for the simple fact of not having to code my own.
    Where am I going wrong?
    function updateMoviePoster(event:VideoEvent):void
                    switch (event.type)
                                    case "playingStateEntered":
                                                    loadPoster.visible = false;
                                                    titlePoster.visible = false;
                                    break;
                                    case "stoppedStateEntered":
                                                    if (loadPoster.visible == false)
                                                                    titlePoster.visible = true;
                                    break;
                                    case "complete":
                                                    titlePoster.visible = true;
                                    break;
    myFLVPlayback.addEventListener(VideoEvent.PLAYING_STATE_ENTERED, updateMoviePoster);
    myFLVPlayback.addEventListener(VideoEvent.STOPPED_STATE_ENTERED, updateMoviePoster);
    myFLVPlayback.addEventListener(VideoEvent.COMPLETE, updateMoviePoster);

    Any suggestions?  I would truly appreciate the help.

  • A better way of building the fixed-length String

    I created the following code to build a fixed length string. I checked other posts for the same topic, but I found mine is better. The code below converts a double numeric value to a fixed length string with padding of white spaces (or other types):
    Line 15 initializes the char array to while space; line 13 creates a character array; lines 17, 18 copy the array created in line 13 to the one initialized in line 15.
    Any comment is welcomed.
    1. import java.text.*;
    2.
    3. public class jformat {
    4.
    5. public static void main(String[] args) {
    6.
    7. char[] fb=new char[14];
    8. char[] tb;
    9. int c, f;
    10. DecimalFormat fmt=new DecimalFormat("########0.00");
    11. double dbl=12345.66;
    12.
    13. tb=fmt.format(dbl).toCharArray();
    14.
    15. for(c=0; c<fb.length; c++) fb[c]=' ';// this line is not required in JDK 1.5
    16.
    17. for(c=tb.length-1, f=fb.length-1; c>=0; c--, f--){
    18.     fb[f]=tb[c];
    19. }
    20. System.out.println(new String(fb));
    21.
    22. }
    23.
    24. }

    Here's a couple of alternatives. One uses a StringBuffer and the second, for Java 5 only, uses the Formatter capabilities.
    import java.text.DecimalFormat;
    public class jformat
        public static void main(String[] args)
            int fieldSize = 14;
            double dbl = 12345.66;
            String dblString = new DecimalFormat("0.00").format(dbl);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < fieldSize - dblString.length(); j++)
                sb = sb.append(' ');
            System.out.println(sb.append(dblString).toString());
             *  The above code works in Java versions 1.3, 1.4, and 1.5.
             *  However, 1.5 provides the Formatter class, and the single
             *  line below can replace the preceeding code.
            System.out.printf("%14.2f%n", dbl);
    }

  • Most effecient way to generate XML output

    What is the most effecient way to generate XML output using ORACLE.
    Presently I am aware of the following:
    1)DBMS_XMLQUERY
    2)DBMS_XMLGEN
    3)SQLX functions
    We are using the first 2 in our database to generate hierarchical XML. Once the XML is generated the XML file is ftp'd to a UNIX box. Because of the file size restrictions in our UNIX bix we decided not to transform the XML output into XML Attributes.
    The attributes are assigned from an XSLT file and the raw XML file is transformed to a file which has attributes.
    My question is:
    In the Oracle Database release 9.2 is there a better efficient way to genarate the final XML file with Attributes from the database side without using the XSLT. If yes, please give an example how to do this?
    Thank You

    In general the SQL/XML publishing functions are the most efficient way..
    DBMS_XMLQUERY is a legacy technology imlimented in Java. The main advantage is that it can be run outside the database in the mid-tier is required.
    DBMS_XMLGEN is a re-implementation of DBMS_XMLQUERY in 'C' which runs inside the database. In most cases it should be much faster than DBMS_XMLQUERY. It provides some features that are still not availalble in the SQL/XML standard such as the ability to generate XML based on a cursor, and the ability to generate recursive output from a connect by query. It is hoped that future versions of the SQL/XML publishing functions will address these issues.
    Both DBMS_XMLGEN and DBMS_XMLQUERY are somewhat limited in terms of generating complex XML documents with multiple levels of nesting.
    The SQL/XML publishing functions are the preferred way of generating XML from relational data. THey provide the ability to generate extremely complex XML structures from relation data and provide full control over element / attributes names, levels of nested etc. Future development projects will focus on enhancing the performance and functionality of the SQL/XML publishing functions rather than the PL/SQL packages
    In general if you can use SQL/XML publishing functions you should do so.
    Does this help....

  • Time difference issue - need a better way

    Hi
    I need to display the difference in time - every day for different time ranges,
    Example 1-2 pm, 4-5 pm, 7-8 pm. And I need the time difference in 2 dates in the past week for each of these ranges everyday.
    example
    Date Diff Range
    01/01/2007 00:01 1-2pm
    01/02/2007 00:03
    01/03/2007 00:10
    01/04/2007 00:05
    01/05/2007 00:23
    01/01/2007 00:10 4-5pm
    01/02/2007 00:13
    01/03/2007 00:11
    01/04/2007 00:15
    01/05/2007 00:23
    01/01/2007 01:10 7-8pm
    01/02/2007 00:13
    01/03/2007 00:10
    01/04/2007 00:11
    01/05/2007 00:21
    One way to achieve this is to have multiple unions for each day and each time range.
    Example:
    select
    from
    where dt_tm between
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 13:00','mm/dd/yyyy hh24:mi:ss')and
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 14:00','mm/dd/yyyy hh24:mi:ss')
    union
    select
    from
    where dt_tm between
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 16:00','mm/dd/yyyy hh24:mi:ss')and
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 17:00','mm/dd/yyyy hh24:mi:ss')
    union
    select
    from
    where dt_tm between
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 19:00','mm/dd/yyyy hh24:mi:ss')and
    to_date(to_char((sysdate-5),'mm/dd/yyyy')||' 20:00','mm/dd/yyyy hh24:mi:ss')
    This will give me the required information for only one day - and that is for sysdate-5.
    I will have same nyumber of unions for each day.
    Is there a better way to accomplish the same?
    Any help appreciated.
    Thx!

    Time difference by date by time range - a better way?

  • Kindly help with rewriting the foll. query in a better way

    IS there a better way of writing the foll query:
    When I have 12,50,00,000 rows in Fact Table, the query is unable to execute. I use more than 200GB of temporary space. But I still get Temp Tablespace Full Error:
    --Foll WITH Clause is to calculate Sum of Debit-Credit to calculate BLNC acc. to Group By values
    WITH crnt_blnc_set
    AS ( SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id AS crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.acntng_entry_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    DECODE (
    f.pstng_typ,
    'Credit', f.pstng_amnt,
    0))
    - SUM (
    DECODE (
    f.pstng_typ,
    'Debit', f.pstng_amnt,
    0))
    AS blnc
    FROM FactTable f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.acntng_entry_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt),
    --Foll WITH Clause calculates Min and Max Date Ids for the Group By conditions as mentioned
    min_mx_dt
    AS ( SELECT /*+parallel(32)*/
    f.hrarchy_dmn_id AS hrarchy_dmn_id,
    f.prduct_dmn_id AS prduct_dmn_id,
    f.crncy_dmn_id AS crncy_dmn_id,
    f.acnt_dmn_id AS acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    MIN (f.val_dt_dmn_id) AS min_val_dt,
    GREATEST (MAX (f.val_dt_dmn_id), 2689) AS max_val_dt
    FROM crnt_blnc_set f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ),
    /*Foll WITH Clause has a Cartesian Join on date_dmn to populate missing entries
    This requirement is because if we have a distinct row for
    hrarchy_dmn_id,
    prduct_dmn_id,
    crncy_dmn_id,
    acnt_dmn_id,
    txn_id,
    txn_src,
    acntng_entry_typ Combination and If wehave a missing entry for that in the max date provided then we actually create those missing entries*/
    slctd_rcrds
    AS ( SELECT /*+ ordered use_nl(d) parallel(mx, 4) */
    mx.hrarchy_dmn_id AS hrarchy_dmn_id,
    mx.prduct_dmn_id AS prduct_dmn_id,
    mx.crncy_dmn_id AS crncy_dmn_id,
    mx.acnt_dmn_id AS acnt_dmn_id,
    mx.txn_id AS txn_id,
    mx.txn_src AS txn_src,
    mx.acntng_entry_typ AS acntng_entry_typ,
    d.date_value AS val_dt,
    d.date_dmn_id AS val_dt_dmn_id
    FROM min_mx_dt mx, date_dmn d
    WHERE mx.min_val_dt <= d.date_dmn_id
    AND mx.max_val_dt >= d.date_dmn_id
    --Foll. WITH clause actually has a outer Join with Firt With Clause to populate the values accordingly
    cmbnd_rcrds
    AS (
    SELECT /*+ USE_HASH(c) */ s.hrarchy_dmn_id AS hrarchy_dmn_id,
    s.prduct_dmn_id AS prduct_dmn_id,
    s.crncy_dmn_id AS crncy_dmn_id,
    s.acnt_dmn_id AS acnt_dmn_id,
    s.txn_id AS txn_id,
    s.txn_src AS txn_src,
    s.acntng_entry_typ AS acntng_entry_typ,
    s.val_dt_dmn_id AS val_dt_dmn_id,
    NVL (c.revsn_dt, s.val_dt) AS revsn_dt,
    NVL (c.blnc, 0) AS blnc,
    0 AS prvs_rcrd_ind
    FROM slctd_rcrds s, crnt_blnc_set c
    WHERE s.hrarchy_dmn_id = c.hrarchy_dmn_id(+)
    AND s.prduct_dmn_id = c.prduct_dmn_id(+)
    AND s.crncy_dmn_id = c.crncy_dmn_id(+)
    AND s.acnt_dmn_id = c.acnt_dmn_id(+)
    AND s.txn_id = c.txn_id(+)
    AND s.txn_src = c.txn_src(+)
    AND s.acntng_entry_typ = c.acntng_entry_typ(+)
    AND s.val_dt_dmn_id = c.val_dt_dmn_id(+))
    Select * from cmbnd_rcrds

    Thanks for the response Alfonso. I have tried that as well. But Create Table as Also uses Temp Storage till it's created. And that again gives the same error as well.
    Anyways I am now trying with a smaller set. This much piece gets executed in Half an hour but the next piece where we pivot the data is taking forever now.
    That piece is as follows:
    (SELECT /*+parallel(8)*/
    f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ
    ORDER BY d.date_value)
    AS crnt_blnc,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_mnth_num
    || d.fin_year_strt
    || d.fin_year_end
    ORDER BY d.date_value)
    / d.mnth_to_dt
    AS mtd_avg,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_year_strt || d.fin_year_end
    ORDER BY d.date_value)
    / yr_to_dt
    AS ytd_avg,
    f.prvs_rcrd_ind AS prvs_rcrd_ind
    FROM cmbnd_rcrds f, thor_date_dmn d
    WHERE d.holidaY_ind = 0 AND f.val_dt_dmn_id = d.date_dmn_id)
    SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS acntng_entry_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    f.crnt_blnc,
    f.mtd_avg,
    f.ytd_avg,
    'EOD TB ETL' AS crtd_by,
    SYSTIMESTAMP AS crtn_dt,
    NULL AS mdfd_by,
    NULL AS mdfctn_dt
    FROM fnl_set f
    WHERE f.prvs_rcrd_ind = 0
    ORDER BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id
    Any other way to pivot this?
    Also I am getting a lot of foll wait events:
    PX Deq Credit :Send blkd
    PX Deq :Table Q Normal
    Direct Path Write Temp
    And Direct Path Read Temp.

Maybe you are looking for

  • Application not working without restart the blackberry

    Dear All, when i get connected through WiFi , the only app working is the browser and the reset of the applications not working , and after restarting the blackberry phone every thing working fine for just 24 hours then it come back down again and i

  • ASP page

    I need help in connection string for ASP. I like to connect ASP page to my oracle 9i database. I am using the following connection string but doesn't work ' Open Connection to the database set conn = Server.CreateObject("ADODB.Connection") conn.Open

  • Adjustment in Value of Assets acquired two years ago

    Hi I have a scenario and i am wondering anybody can help or guide me. Asset were procured two years back which were acquired through PO. User came back today that they actual asset quantity was 98 instead of 100 and now they want to adjust GR to 98 w

  • Customer Exit Variable on 0CO_AREA

    Hello Experts, I have a requirement to create a customer exit variable on 0CO_AREA to return values for 0CO_AREA based on the 0PROFIT_CTR which will be entered by user in a BW query. As CO_AREA is compounding on PROFIT_CTR, I am not sure if we can do

  • ICal Server Utility...any point?

    I've got our calendar server up and running. Its an OD replica from our primary OD master. Workgroup manager shows all my users and groups. Since we have multiple boardrooms which need to be bookable I am trying to use the iCal Server Utility. To set