XML Generation using a sql query in an efficient way -Help needed urgently

Hi
I am facing the following issue while generating xml using an sql query. I get the below given table using a query.
     CODE      ID      MARK
==================================
1 4 2331 809
2 4 1772 802
3 4 2331 845
4 5 2331 804
5 5 2331 800
6 5 2210 801
I need to generate the below given xml using a query
<data>
<CODE>4</CODE>
<IDS>
<ID>2331</ID>
<ID>1772</ID>
</IDS>
<MARKS>
<MARK>809</MARK>
<MARK>802</MARK>
<MARK>845</MARK>
</MARKS>
</data>
<data>
<CODE>5</CODE>
<IDS>
<ID>2331</ID>
<ID>2210</ID>
</IDS>
<MARKS>
<MARK>804</MARK>
<MARK>800</MARK>
<MARK>801</MARK>
</MARKS>
</data>
Can anyone help me with some idea to generate the above given CLOB message

not sure if this is the right way to do it but
/* Formatted on 10/12/2011 12:52:28 PM (QP5 v5.149.1003.31008) */
WITH data AS (SELECT 4 code, 2331 id, 809 mark FROM DUAL
              UNION
              SELECT 4, 1772, 802 FROM DUAL
              UNION
              SELECT 4, 2331, 845 FROM DUAL
              UNION
              SELECT 5, 2331, 804 FROM DUAL
              UNION
              SELECT 5, 2331, 800 FROM DUAL
              UNION
              SELECT 5, 2210, 801 FROM DUAL)
SELECT TO_CLOB (
             '<DATA>'
          || listagg (xml, '</DATA><DATA>') WITHIN GROUP (ORDER BY xml)
          || '</DATA>')
          xml
  FROM (  SELECT    '<CODE>'
                 || code
                 || '</CODE><IDS><ID>'
                 || LISTAGG (id, '</ID><ID>') WITHIN GROUP (ORDER BY id)
                 || '</ID><IDS><MARKS><MARK>'
                 || LISTAGG (mark, '</MARK><MARK>') WITHIN GROUP (ORDER BY id)
                 || '</MARK></MARKS>'
                    xml
            FROM data
        GROUP BY code)

Similar Messages

  • Problem for xml generation using DBMS_XMLGEN

    Hi All,
    i have problem during xml generation using Any help would be highly appreciate
    how could we publish xml data using data base API DBMS_XMLGEN in oracle applications (APPS) i.e. at 'View Output" using
    Any help would be highly appreciate.
    Let me know if need more explanation, this is High priority for me.
    Thanks and Regards,
    [email protected]
    Message was edited by:
    user553699

    You can set the null attribute to true , so that the tag appears in your XML
    see the statement in Bold.
    DECLARE
    queryCtx dbms_xmlquery.ctxType;
    result CLOB;
    BEGIN
    -- set up the query context
    queryCtx := dbms_xmlquery.newContext(
    'SELECT empno "EMP_NO"
    , ename "NAME"
    , deptno "DEPT_NO"
    , comm "COMM"
    FROM scott.emp
    WHERE deptno = :DEPTNO'
    dbms_xmlquery.setRowTag(
    queryCtx
    , 'EMP'
    dbms_xmlquery.setRowSetTag(
    queryCtx
    , 'EMPSET'
    DBMS_XMLQUERY.useNullAttributeIndicator(queryCtx,true);
    dbms_xmlquery.setBindValue(
    queryCtx
    , 'DEPTNO'
    , 30
    result := dbms_xmlquery.getXml(queryCtx);
    insert into clobtable values(result);commit;
    dbms_xmlquery.closeContext(queryCtx);
    END;
    select * from clobtable
    <?xml version = '1.0'?>
    <EMPSET>
    <EMP num="1">
    <EMP_NO>7499</EMP_NO>
    <NAME>ALLEN</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM>300</COMM>
    </EMP>
    <EMP num="2">
    <EMP_NO>7521</EMP_NO>
    <NAME>WARD</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM>500</COMM>
    </EMP>
    <EMP num="3">
    <EMP_NO>7654</EMP_NO>
    <NAME>MARTIN</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM>1400</COMM>
    </EMP>
    <EMP num="4">
    <EMP_NO>7698</EMP_NO>
    <NAME>BLAKE</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM NULL="YES"/>
    </EMP>
    <EMP num="5">
    <EMP_NO>7844</EMP_NO>
    <NAME>TURNER</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM>0</COMM>
    </EMP>
    <EMP num="6">
    <EMP_NO>7900</EMP_NO>
    <NAME>JAMES</NAME>
    <DEPT_NO>30</DEPT_NO>
    <COMM NULL="YES"/>
    </EMP>
    </EMPSET>
    http://sqltech.cl/doc/oracle9i/appdev.901/a89852/d_xmlque.htm

  • Using a SQL Query in an Alert and Matching a String

    I've created an alert in 12.0.4 using a SQL Query and the field that I'm trying to match is a string.  Originally the query returned multiple rows but when the alert still didn't fire, I modified the query WHERE clause to return only one row:
    NAME                                RESPONSE
    Are area lights working?            No
    My expression in the metric is RESPONSE.  In the Monitor I'm matching a string equal to No.  (Do I need double quotes around the matchvalue?  Single quotes?  No quotes?)  The metric is in the 15min scan group, the role is xMII Developers and I'm in that role. The monitor alert string is ' =  '.  Both metric and monitor are active and I've subscribed to the monitor.  Other alerts in the 15min scan group (all based on tag queries) are firing off properly.
    Why is nothing showing up in the Alert Log?
    David Macindoe

    David,
    Did you figure out the answer?  If not, I will try to find someone to address your question.
    Mike

  • Can we use Data Pump to export data, using a SQL query, doing a join

    Folks,
    I have a quick question.
    Using Oracle 10g R2 on Solaris 10.
    Can Data Pump be used to export data, using a SQL query which is doing a join between 3 tables ?
    Thanks,
    Ashish

    Hello,
    No , this is from expdp help=Y
    QUERY                 Predicate clause used to export a subset of a table.
    Regards

  • How to use this sql query in oracle?

    Hi all,
    i am using one sql query that is
    SELECT @ToDate = '2012-10-03 00:00:00.000'
    select @BetweenDate = DATEADD(MM,-1,@ToDate)
    select @FromDate = DATEADD(m,DATEDIFF(m,0,@BetweenDate),0)
    SELECT @ToDate = DATEADD(month, ((YEAR(@BetweenDate) - 1900) * 12) + MONTH(@BetweenDate), -1)
    so @todate value is = '2012-10-03 00:00:00.000'
    so in @betweendate value will come 1 month before like '2012-09-03 00:00:00.000'
    again in @fromdate value will come like that '2012-09-01 00:00:00.000' means first date of @betweendate
    and again @todate value will come like that '2012-09-30 00:00:00.000' means last date of @betweendate
    it's happening in sql and i have to use same logic in oracle also.
    how to use it??
    thanks

    declare
    todate date:= to_date('2012-10-03 00:00:00','yyyy-mm-dd hh:mi:ss');
    betwendate date := add_months(todate,-1);
    for datediff / additions you can direct subtract/add two different date variables
    like
    datediff = betweendate -todate
    dateadd := todate+1;

  • I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work

    Hi,
    I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work
    (fault number -2147217900)
    I want to search for a value in a ms access table , if it exist i want to update it, if not i want to insert a new row.
    Working with LabView 7.1, database con. toolset.
    Who can HELP?
    Thanks a lot
    Marco

    Hello,
    I think that If exist is not a standar SQL command (I know it exists I think in Oracle and SQL server), MS access doesn't support it, so I think the best way to do it is first make a Select and then either an Update or an insert, sorry...
    Paulo

  • Using multiple sql query

    Im writing a jsp that pulls data from the database and loads it into dropdown-list looks like this:
    <select name="Source">
    <%
    conn = DriverManager.getConnection(url, username, password);
    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery("SELECT BBCourseID(Sroffer.SrofferID)course_name, SrofferSchedule_Faculty.FacultyID AS FacultyID FROM SrofferSchedule_Faculty srofs JOIN SrofferScheduleID sros ON srofs.SrofferScheduleID= sro.SrofferScheduleID JOIN Sroffer sro ON sro.SrofferID= sros.SrofferID WHERE srofs.FacultyID=IDnumber");
    rs.beforeFirst();
    while (rs.next()) {%>
    <option value="<%=courseid=rs.getString("BBCourseID")%>"><%=courseid%> <%=rs.getString("course_name")%></option>
    <%}
    %>
    </select>
    Problem is, I have to pull the FacultyID from cams using this sql query
    ("SELECT FacultyID FROM FacultyPortal WHERE PortalAlias="") berfore i can run the query above. Don't know how to do this in a jsp
    Edited by: JohnsonJ on Mar 26, 2009 5:53 PM

    You know how to get a connection and how to execute a query and how to process the resultset - so what's standing in your way of doing that for the faculty ID?
    Isn't there a join you can do to get that in one query?
    And finally - you really shouldn't do this in a JSP, use a servlet to package the result up in some Java Collection and process it with JSTL tags.

  • Read XML File Using PL/SQL

    Hi,
    I have to read a XML file using PL/SQL. I am new to this so please explain in easy steps.
    Regards,
    SF

    STEP - 2
    SQL>
    SQL> DECLARE
      2    l_ctx dbms_xmlsave.ctxType ;
      3    l_xml CLOB :=
      4  '<?xml version="1.0" encoding="UTF-8" ?>
      5  <NewDataSet>
      6      <ROW>
      7          <DEPARTMENT>BA52</DEPARTMENT>
      8          <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
      9          <LOCATION>Australia</LOCATION>
    10          <MAY_2006>21668</MAY_2006>
    11      </ROW>
    12      <ROW>
    13          <DEPARTMENT>BA501</DEPARTMENT>
    14          <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
    15          <LOCATION>China</LOCATION>
    16          <MAY_2006>8166</MAY_2006>
    17      </ROW>
    18      <ROW>
    19          <DEPARTMENT>BA522</DEPARTMENT>
    20          <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
    21          <LOCATION>Australia</LOCATION>
    22          <MAY_2006>21668</MAY_2006>
    23      </ROW>
    24  </NewDataSet>' ;
    25  BEGIN
    26      l_ctx := dbms_xmlsave.newContext(targetTable => 'XML_INSERT');
    27      dbms_output.put_line(dbms_xmlsave.insertXML(ctxHdl => l_ctx,
    28                                                  xDoc   => l_xml) ||
    29                           ' rows inserted.');
    30      dbms_xmlsave.closeContext(l_ctx);
    31  END;
    32  /
    3 rows inserted.
    PL/SQL procedure successfully completed.Regards.
    Satyaki De.

  • How to get a week number  for the year using oracle sql query?

    hi everyone,
    i have the requirement to find the week number for the calender..
    so that week number should start with 01 when the year starts and it should end with week end date(that is first saturday of the january month).. so next week number starts with sunday and ends with saturday ,continously.. in the end date of the year it should not be 'saturday' but week number should end with last date of the year.. again in the next year it should start with '01'.
    for example:
    01-JAN-13 tuesday 01
    02-JAN-13 wednesday 01
    03-JAN-13 thursday 01
    04-JAN-13 friday 01
    05-JAN-13 saturday 01
    06-JAN-13 sunday 02
    07-JAN-13 monday 02
    26-DEC-13 thursday 52
    27-DEC-13 friday 52
    28-DEC-13 saturday 52
    29-DEC-13 sunday 53
    30-DEC-13 monday 53
    31-DEC-13 tuesday 53
    01-JAN-14 wednesday 01
    02-JAN-14 thursday 01
    how can i achieve this, can anyone please help me out on this..
    i have a query that starts with 01 when year starts but it gives problem in the end of the year .. described below with a query..
    select mydate,
    to_char(mydate,'day') as weekday,
    to_char(next_day(mydate,'sunday'),'iw') as week_num
    FROM ( SELECT TRUNC (SYSDATE, 'yy') - 1 + LEVEL AS mydate
    FROM dual
    CONNECT BY LEVEL <= (SELECT TRUNC (ADD_MONTHS (SYSDATE, 24), 'yy')
    - TRUNC (SYSDATE, 'yy')
    FROM DUAL))
    this query gives date, weekday and week_num for 2 years 2013 and 2014,
    when i run this query ,at the end of the 2013 it gives the result as,
    26-DEC-13     thursday      52
    27-DEC-13     friday      52
    28-DEC-13     saturday      52
    29-DEC-13     sunday      01
    30-DEC-13     monday      01
    31-DEC-13     tuesday      01
    01-JAN-14     wednesday     01
    02-JAN-14     thursday      01
    for dates 29 ,30,31st it should give 53 .. how can i achieve that using this this query .. can any one help me out on this please...
    thanks,
    pradeep

    I tried with the IW ...
    it is giving week_id for the year.
    select
    mydate,
    to_char(mydate,'day'),
    case when mydate between trunc(mydate,'yyyy') and next_day(trunc(mydate,'yyyy'),'saturday')
    then to_number(to_char(mydate,'yyyy')||to_char(trunc(mydate,'yyyy'),'iw'))
    when mydate between next_day(trunc(mydate,'yyyy'),'saturday') and trunc(add_months(trunc(mydate,'yyyy'),12)-1,'d')-1
    then to_number(to_char(mydate,'yyyy')||to_char(next_day(mydate,'sunday'),'iw'))
    when mydate between trunc(add_months(trunc(mydate,'yyyy'),12)-1,'d') and add_months(trunc(mydate,'yyyy'),12)-1
    then to_number(to_char(mydate,'yyyy')||to_char(trunc(add_months(trunc(mydate,'yyyy'),12)-1,'d')-1,'iw')+1) end as WEEK_ID
    FROM ( SELECT TRUNC (SYSDATE, 'yy') - 1 + LEVEL AS mydate
    FROM dual
    CONNECT BY LEVEL <= (SELECT TRUNC (ADD_MONTHS (SYSDATE, 24), 'yy')
    - TRUNC (SYSDATE, 'yy')
    FROM DUAL
    ))

  • SQL Query for members of dynamic group - Need to include Name, Path and Type

    Hello,
    I built a custom dynamic group that has all my SQL databases in it using SCOM 2012 SP1.  The group works fine as I can see the Name(ie, Database name), Health State, Path (ie, hostname/instance) and Types (ie; SQL 2005).  Now I'm trying to
    build a custom report based off this same information using a SQL query.   I'm no DBA and could use some help.  So far this is what i have
    use
    select
    SourceObjectDisplayName as
    'Group Name',
    TargetObjectDisplayName,TargetObjectPath
    from RelationshipGenericView
    where isDeleted=0
    AND SourceObjectDisplayName
    like
    'SQL_Databases_All'
    ORDERBY TargetObjectDisplayName
    This gets me the Group Name (which i really don't care about), database name, and hostname/instance. What I am missing is the Health State and most importantly the Type (ie, SQL Server 2005 DB, SQL Server 2008DB).
    If someone could assist me here I would appreciate it. I believe I need to do some type of INNER JOIN but have no idea where the SQL type info lives or the proper structure to use. Thanks
    OperationsManager

    Here's the updated Query for OpsMan 2012 R2:
    To find all members of a given group (change the group name below):
    select SourceObjectDisplayName as 'Group Name', TargetObjectDisplayName as 'Group Members' 
    from RelationshipGenericView 
    where isDeleted=0 
    AND SourceObjectDisplayName = 'Agent Managed Computer
    Group' 
    ORDER BY TargetObjectDisplayName

  • Creating XML report using PL/SQL Stored Procedure

    Hi Friends,
    I am working on an xml report with the xml source as PL/SQL Stored Procedure.
    I am referring the exercise shown in the following link to understand the process:
       http://orclapp.blogspot.com/2012/02/developing-xml-publisher-report-using.html
    In the example shown in the above link I could not understand the following:
    1) In the following procedure, the out parameter 'retcode' is not used at all.
       What is the importance of this parameter.
        PROCEDURE REPORT (errbuf  OUT VARCHAR2, retcode  OUT VARCHAR2, p_product_id   IN     NUMBER)
    2)  After the xml data is prepared and put to 'l_result' Clob variable, the following
        Loop is executed. I am not able to appreciate why the following loop is required.
         LOOP
             EXIT WHEN l_length = l_retrieved;
             IF (l_length - l_retrieved) < 32000
             THEN
                SELECT SUBSTR (l_result, l_retrieved + 1) INTO l_xmlstr FROM DUAL;
                l_retrieved := l_length;
                fnd_file.put_line (fnd_file.output, l_xmlstr);
             ELSE
                SELECT SUBSTR (l_result, l_retrieved + 1, l_offset)
                  INTO l_xmlstr
                  FROM DUAL;
                l_retrieved := l_retrieved + l_offset;
                fnd_file.put_line (fnd_file.output, l_xmlstr);
             END IF;
         END LOOP;
    3) In the example it is not explained how the concurrent program gets the xml data?
       I assume it is written to a file using the following line of code:
        fnd_file.put_line (fnd_file.output, l_xmlstr);
       I would appreciate if anyone can throw some light into my above queries so that I can understand the process clearly.
    Thanks & Regards
    Hawker

    Hi 32000 in the code is a 'safe' size smaller than the max available 32767, the loops purpose is to move through the entire thing in chunks that will be manageable in the limits of the data type.
    Btw; if you are in Oracle e-business suite then you can also use Oracle reports very simply to create XML output.
    If you have reports developer all you need to do is put raw sql (without any 'artifice' to create XML) in the report SQL and then set the reports output to XML in the program definition in Oracle e-business.
    best regards,
    Robert.

  • Is there a way to consolidate calculations used in SQL Query Data Sets?

    I am building SQL Query Data Sets against multiple DB Views which all have different date formats. I have the date parameter working well, but want to consolidate the changes that I have to do to it especially for the quarter. For example the SQL against a monthly view would use "where year_month > to_char(:ST_DATE, 'YYYY-MM')" which is not too hard, but to make that work for the quarterly view I need several concats and a decode to get a "> '2012-Q2'". I would like not to have to do this within every where clause. I had put this into a global element hoping to use that in a filter for the data set, but the filter does not have access to global elements only parameters.
    Is there any way to refer to a calculated global element from the data set to do this? I am using Layout Templates, so even if I wanted to I could not do the condition within the template.
         Thanks,
         Rick

    Change the following line to include the red coloured parts
    <div class="MasterColumn" spry:repeat="ds4" spry:setrow="ds4" spry:hover="MasterColumnHover" spry:select="MasterColumnSelected">
      <span>{Dsp_#}</span><span>{Dsp_WkDay}</span><span>{Dsp_Event}</span>
    </div>
    The add the following style rule to your document:
    .MasterColumn span {
        display: inline-block;
    I hope this helps.
    Ben

  • Use an SQL Query in a backing bean

    hi,
    I like to know how to run an SQL query in a backing bean method, this being the code I tried , his goal is to fill the field "cin" with data coming from my database, here is the Code:
    public String cb2_action() {
    BindingContainer bindings = getBindings();
    OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert");
    Object result = operationBinding.execute();
    if (!operationBinding.getErrors().isEmpty()) {
    return null;
    DCIteratorBinding dciter =(DCIteratorBinding) bindings.get("PersonneView1Iterator");
    Row row=dciter.getCurrentRow();
    Statement stmt = this.getDBTransaction().createStatement(1);
    try {
    ResultSet rs = stmt.executeQuery("select max(cin) from personne");
    while( rs.next() ){
    row.setAttribute("cin", rs.getInt(1)+1);
    } catch (SQLException ex) {
    ex.printStackTrace();
    return "go";
    at run time it give an error at this line : Statement stmt = this.getDBTransaction().createStatement(1);
    please check and correct me
    thanks in advance

    Hi,
    Initially I would like to say that this should not be used if you are trying to get a PrimaryKey as it would cause serious concurrency issues.
    For example lets say that you want whenever you create a new Employee to set his DepartmentId equal to the max department.
    We could create a readOnly VO (lets name it MaxDepartmentId) with a query that returns the max departmentId:
    select max(Department_Id) as maxDep from DepartmentsAfter that we need to add the MaxDepartmentId VO as a ViewAccessor in our Employees Vo,
    override the create() method in the EmployeesRowImpl and add some code like this:
    public class EmployeesRowImpl extends ViewRowImpl {
        @Override
        protected void create(AttributeList attributeList) {
            Row r=getMaxDepartmentId().first();
            if(r!=null){
                 Number max=(Number)r.getAttribute("Maxdep");
                 attributeList.setAttribute("DepartmentId", max);
            super.create(attributeList);
    }That's all.
    If you run this you will see that when you create a new employee it has a default value.
    Gabriel.

  • Check the hints used in SQL Query (Parallel, First_Rows)

    Hi,
    I have used above hints in my sql query and found no difference in execution time.
    I just want to know whether the hints are used in my sql are not.
    Could you please let me know where to check for it.
    Thanks in advance

    Can you post the SQL which uses these hints and the execution plan with and without those hints here? Then only community can help you find out if the hints are really used or not.
    Please use code tags to preserve the format of execution plan.
    Edited by: Satish Kandi on Jun 23, 2009 5:37 PM

  • How to create a Folder using a SQL Query?

    Hi
    How can I create a Folder (eg. C:\MyNewFolder) using SQL Query?

    Hi,
    I added some code in order to get the result from the xp_cmdshell command
    This returns null if successfull, if an error occurs returns the error message. May be useful instead of getting an sql error
    Code Snippet
    declare @cmdpath nvarchar(60), @Location nvarchar(100), @message nvarchar(max)
    set @Location = N'C:\Temp\Temp5'
    set @cmdpath = 'MD '+ @Location
    Create table #result
    result nvarchar(255)
    insert into #result (result) exec master.dbo.xp_cmdshell @cmdpath
    select @message = ISNULL(@message + ' - ','') + result from #result where result is not null
    select @message
    drop table #result
    Eralper
    http://www.kodyaz.com

Maybe you are looking for

  • How to connect to wifi manually

    i need help. im trying to connect my ipod to my wireless conenction and it wont work. it used to conenct to it all the time. i try putting my password and it keeps saying "unable to connect". i just updated my ipod to the newest update. i have a 4th

  • ClassCastException in InvocableMap.ParallelAwareAggregator

    I am using InvocableMap.ParallelAwareAggregator to sort results set on cache server side. But I'm keep getting ClassCastException like below : 2008-02-14 17:33:28.603 Oracle Coherence DC 3.3.1/389p1 <Info> (thread=main, member=n/a): Connected to 10.5

  • Infopackage in process chain failing due to short dump on regular basis.

    HI Experts, There is a daily process chain in which one of the element (infopackage) fails due to short dump on regular basis (At least twice in a week) please find the message below Runtime Errors         DBIF_RSQL_SQL_ERROR Exception              C

  • I want to order recovery media for my touchsmart tm2-2090ee ?

    Dear HP, Original HDD has stopped (no more workable), I purchased another HDD and I want to order the recovery media to return to original PC configuration. I purchased the laptop from Middle east region - Jordan , and now I am living in USA. type of

  • TABLE : Display changes for materials

    Hi, There is any table to display changes of a material (With the table and field name modified) Thanks