Putting the results of a PL/SQL package on a .jspx page

Hi, I have customer who wants to replace a cgi script's results with a .jspx page. Nothing fancy, just a straight vertical text dump of text returned from a PLSQL PKG into say an af:ouputText or af:outputFormatted. All within an af:panelGroupLayout vertical.
I understand UIs and ADF Faces pretty well but when it comes to database data displaying into components, I am green.
So, how would I declaratively in Jdev 11.1.1.3, create databindings, controls, etc. and dump display them in an af:outputText? All of the Tutorials I have seen show database tables etc., not PL/SQL packages. Can you please outline the steps for doing the databinding and controls things so that I can drop them onto a .jspx page/component? Please from the standpoint of using the PL/SQL package shown below. I would be forever grateful.
Thanks!!!!
Here is the PL/SQL package:
FUNCTION get_tsr_details(p_incident_no VARCHAR2)
RETURN CLOB ;
END WRS_KM_TSR_PKG;
Here is the Body:
FUNCTION get_tsr_details(p_incident_no VARCHAR2)
RETURN CLOB
IS
CURSOR cu_tsr
IS
select ('TSR#: '||tsr.incident_number||chr(10)||
'Assigned: '||tsr.owner||chr(10)||
'Status: ' || tsr.status || CHR (10) ||
'-------------------------------------------------------------'||chr(10)||
'Date: '|| csi.incident_date||chr(10)||
'Title: '||tsr.summary||chr(10)||
--'Name: '||decode(ccp.contact_type, 'EMPLOYEE',fnd2.full_name ,'PARTY_RELATIONSHIP',sp.party_name ) ||chr(10)||
'Company: '||tsr.party_name ||chr(10)||
'License#: '||tsr.license_number||chr(10)||
'Product Name: '||tsr.item_description ||chr(10)||
'HostOS: '||csi.operating_system||' '||chr(10)||
'HostOS Rev: '||csi.operating_system_version||chr(10)||
'Arch Family: '||tsr.arch_family||chr(10)||
'Processor Family: '||tsr.processor_family||chr(10)||
     'Processor: ' ||tsr.processor_family||chr(10)||
'BSP: '||tsr.bsp||chr(10)||
     'BSP Version: '||tsr.bsp_version||chr(10)||
     'SPR Number: '||tsr.spr_number) tsr_detail,
tsr.incident_number,tsr.incident_id
from wrs_km1_tsr_ksm_v tsr, cs_incidents_all_b csi
where tsr.incident_id = csi.incident_id
--and    tsr.incident_id = p_incident_id;
and tsr.incident_number = p_incident_no;
CURSOR cu_notes(l_incident_id number,l_incident_no varchar2)
IS
SELECT ('TSR: '||l_incident_no||CHR(10)||
'-------------------------------------------------------------'||CHR(10)||
'Date Created: '||creation_date||' Created By: '||entered_by_name||CHR(10)||
'Visibility: '||note_status_meaning||CHR(10)||
'Status: '||note_type_meaning||CHR(10)||
'Transaction Description'||CHR(10)||CHR(10)||
notes||CHR(10)||
notes_detail) not_dtl
FROM jtf_notes_vl
WHERE source_object_id= l_incident_id
AND     source_object_code = 'SR'
ORDER BY creation_date aSC;
l_tsr_details CLOB;
l_incident_no cs_incidents_all_b.incident_number%TYPE;
l_incident_id cs_incidents_all_b.incident_id%TYPE;
BEGIN
FOR ru_tsr IN cu_tsr
LOOP
l_tsr_details := l_tsr_details ||ru_tsr.tsr_detail||CHR(10) ;
l_tsr_details := l_tsr_details ||'********************Transaction*******************';
l_incident_no := ru_tsr.incident_number;
l_incident_id := ru_tsr.incident_id;
FOR ru_notes in Cu_notes(l_incident_id,l_incident_no)
LOOP
l_tsr_details := l_tsr_details ||CHR(10)||ru_notes.not_dtl;
END LOOP;
EXIT;
END LOOP;
--INSERT INTO AA VALUES(l_tsr_details);
--COMMIT;
RETURN l_tsr_details;
EXCEPTION
WHEN OTHERS THEN
RETURN l_tsr_details ;
END get_tsr_details;
END WRS_KM_TSR_PKG;

One solution is to write a Java class that has a method that nvokes the PL/SQL procedure and then return a String.
Then you can expose that Java class as a data control and drag the result of the method onto the page.
A bit about JDBC with PL/SQL and CLOB:
http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/basic.htm#i1008346
http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oralob.htm
And a bit about exposing a Java class as a data control:
http://blogs.oracle.com/shay/2009/07/java_class_data_control_and_ad.html

Similar Messages

  • I would like to put the results of a proc on a local database into a table in my azure db. What is the best way to do this?

    I would like to put the results of a proc on a local database into a table in my azure db.  What is the best way to do this?  I dont see the ability to link.  The local db is on my desktop and is mssql12.
    McC

    I am not sure if i set up the linked server correctly here is the schema and an attempt to run a select and the resulting error:
    SELECT  *
    FROM  [CN5E6E9LM2.DATABASE.WINDOWS.NET,1433].[Mkerr_db].dbo.addr
    OLE DB provider "SQLNCLI11" for linked server "CN5E6E9LM2.DATABASE.WINDOWS.NET,1433" returned message "Unspecified error".
    Msg 40515, Level 16, State 2, Line 1
    Reference to database and/or server name in 'Mkerr_db.sys.sp_tables_info_90_rowset_64' is not supported in this version of SQL Server.
    McC

  • How do I create a 1d array that takes a single calculation and insert the result into the first row and then the next calculation the next time the loop passes that point and puts the results in thsecond row and so on until the loop is exited.

    The attached file is work inprogress, with some dummy data sp that I can test it out without having to connect to equipment.
    The second tab is the one that I am having the problem with. the output array from the replace element appears to be starting at the index position of 1 rather than 0 but that is ok it is still show that the new data is placed in incrementing element locations. However the main array that I am trying to build that is suppose to take each new calculation and place it in the next index(row) does not ap
    pear to be working or at least I am not getting any indication on the inidcator.
    Basically what I am attempting to do is is gather some pulses from adevice for a minute, place the results for a calculation, so that it displays then do the same again the next minute, but put these result in the next row and so on until the specifiied time has expired and the loop exits. I need to have all results displayed and keep building the array(display until, the end of the test)Eventually I will have to include a min max section that displays the min and max values calculated, but that should be easy with the min max function.Actually I thought this should have been easy but, I gues I can not see the forest through the trees. Can any one help to slear this up for me.
    Attachments:
    regulation_tester_7_loops.vi ‏244 KB

    I didn't really have time to dig in and understand your program in depth,
    but I have a few tips for you that might things a bit easier:
    - You use local variables excessively which really complicates things. Try
    not to use them and it will make your life easier.
    - If you flowchart the design (very similar to a dataflow diagram, keep in
    mind!) you want to gather data, calculate a value from that data, store the
    calculation in an array, and loop while the time is in a certain range. So
    theres really not much need for a sequence as long as you get rid of the
    local variables (sequences also complicate things)
    - You loop again if timepassed+1 is still less than some constant. Rather
    than messing with locals it seems so much easier to use a shiftregister (if
    absolutely necessary) or in this case base it upon the number of iterations
    of the loop. In this case it looks like "time passed" is the same thing as
    the number of loop iterations, but I didn't check closely. There's an i
    terminal in your whileloop to read for the number of iterations.
    - After having simplified your design by eliminating unnecessary sequence
    and local variables, you should be able to draw out the labview diagram.
    Don't try to use the "insert into array" vis since theres no need. Each
    iteration of your loop calculates a number which goes into the next position
    of the array right? Pass your result outside the loop, and enable indexing
    on the terminal so Labview automatically generates the array for you. If
    your calculation is a function of previous data, then use a shift register
    to keep previous values around.
    I wish you luck. Post again if you have any questions. Without a more
    detailed understanding of your task at hand it's kind of hard to post actual
    code suggestions for you.
    -joey
    "nelsons" wrote in message
    news:[email protected]...
    > how do I create a 1d array that takes a single calculation and insert
    > the result into the first row and then the next calculation the next
    > time the loop passes that point and puts the results in thsecond row
    > and so on until the loop is exited.
    >
    > The attached file is work inprogress, with some dummy data sp that I
    > can test it out without having to connect to equipment.
    > The second tab is the one that I am having the problem with. the
    > output array from the replace element appears to be starting at the
    > index position of 1 rather than 0 but that is ok it is still show that
    > the new data is placed in incrementing element locations. However the
    > main array that I am trying to build that is suppose to take each new
    > calculation and place it in the next index(row) does not appear to be
    > working or at least I am not getting any indication on the inidcator.
    >
    > Basically what I am attempting to do is is gather some pulses from
    > adevice for a minute, place the results for a calculation, so that it
    > displays then do the same again the next minute, but put these result
    > in the next row and so on until the specifiied time has expired and
    > the loop exits. I need to have all results displayed and keep building
    > the array(display until, the end of the test)Eventually I will have to
    > include a min max section that displays the min and max values
    > calculated, but that should be easy with the min max function.Actually
    > I thought this should have been easy but, I gues I can not see the
    > forest through the trees. Can any one help to slear this up for me.

  • Is it possible to put the results from a query in a variable to use in the bean class?

    Hello, I'm using JDeveloper 12.1.2.0.0
    I would like to keep the result of my queries (the method i created in the AppModule) in a RichTable or other type of variable so i can have the results stored and i don't have to do unnecessary queries after. I don't think the query is the problem but keeping the results.
    I've tried to do that by using this:
        public String testVFactSales(String conditions) {
            PreparedStatement query = getDBTransaction().createPreparedStatement("" + "select * from v_fact_sales " + conditions, 0);
            //ResultSet rs;
            ResultSet result;
            //RichTable result;
            //String result = null;
            try {
                //query.setString(1, conditions);
                // query.execute();
                query.execute();
                result = query.getGeneratedKeys();
                query.close();
                System.out.println("Result: " + result.toString());
                return result.toString();
            } catch (SQLException e) {
                e.printStackTrace();
            return "";
    As you can see, i've already tried some solutions but so far i only get errors (cannot convert or null exception, when i try to put the result in a richtable in my bean class)
    Any ideas?
    This is very important for me, since it would improve the performance of my project a lot.
    Regards,
    Frederico.

    Hey Arunkumar,
    I came to this conclusion since i'm using binding variables with my where clauses.
    I've measured the time and i get really bad time responses.
    This is my main table query, where all the others selections will be filter the search in this table:
    SELECT VFactSalesNew.N_SALES,                              
           VFactSalesNew.QUANTITY,                              
           VFactSalesNew.PRICE,                               ,                              
           VFactSalesNew.FK_STORE,                              
           VFactSalesNew.ID_ANO,                              
           VFactSalesNew.QUARTER   
    FROM V_FACT_SALES_NEW VFactSalesNew                              
    WHERE                                          
    ((nvl(:var_dimCoin,'0') ='0' OR FK_COIN IN (select * from THE(select cast( in_list(:var_dimCoin) as mytableType ) from dual ) a) )                                                   
    AND                                                 
    (nvl(:var_dimProduct,'0') ='0' OR FK_PRODUCT IN (select * from THE(select cast( in_list(:var_dimProduct) as mytableType ) from dual ) a) )                                                  
    AND                                                 
    (nvl(:var_dimCustomer,'0') ='0' OR FK_CUSTOMER IN (select * from THE(select cast( in_list(:var_dimCustomer) as mytableType ) from dual ) a) )                                                 
    AND                                                 
    (nvl(:var_dimStore,'0') ='0' OR FK_STORE IN (select * from THE(select cast( in_list(:var_dimStore) as mytableType ) from dual ) a) )                                                
    AND                                                 
    (nvl(:var_dimSeller,'0') ='0' OR FK_SELLER IN (select * from THE(select cast( in_list(:var_dimSeller) as mytableType ) from dual ) a) )                                                  
    AND                                                 
    (nvl(:var_dimProject,'0') ='0' OR FK_PROJECT IN (select * from THE(select cast( in_list(:var_dimProject) as mytableType ) from dual ) a) )                                                  
    AND                                                 
    (nvl(:var_ano, '0') ='0' OR ID_ANO IN (select * from THE(select cast( in_list(:var_ano) as mytableType ) from dual ) a) )                                                  
    AND                                                 
    (nvl(:var_treemap,'0') ='0' OR PK_REGION IN (select * from THE(select cast( in_list(:var_treemap) as mytableType ) from dual ) a) )                                                  

  • How to merge text files and put the result in a text file.

    Hi,
    I am trying to merge the files(text) using OWB and I would like to put the result in a file. Could any one please explain how to do this.
    Thanks and regards
    Gowtham Sen.

    using the unix commnad 'cat' along with the redirect '>>' will concat the files into one target
    #this will create the target file and over-write it if it existed already
    cat file1 > target
    ##Now add the rest of the files to the target, without over-writing
    cat file2 >>target
    cat file3 >>target
    cat file16 >> target
    You can then use an external table on the target file.
    A nicer way would be to user a 'for loop', but this will work fine.

  • How do i put the result of a sum in a variable ?

    Hi All...
    I have two columns in my template, one is debit and another one is credit...
    I did a sum in debit column and a sum in the credit column...
    Now i need to subtract the sum of debit from the sum of credit,
    i was thinkin about put these results in a variable (something like make a "sumResultA" and "sumResultB" and make a field like this <?((sumResultA) - (sumResultB))?>...
    so... how do i put the result of a sum in a variable ???

    <?xdoxslt:set_variable($_XDOCTX, 'variablesumResultA', (sumResultA))?>
    <?xdoxslt:set_variable($_XDOCTX, 'variablesumResultB', (sumResultB))?>
    <?xdoxslt:set_variable($_XDOCTX, 'variablesumResultAB', ((sumResultA) - (sumResultB)))?>to set the, use as above.
    to display them
    <?xdoxslt:get_variable($_XDOCTX, 'variablesumResultB')?>
    <?xdoxslt:get_variable($_XDOCTX, 'variablesumResultA')?>
    <?xdoxslt:get_variable($_XDOCTX, 'variablesumResultAB')?>

  • How can I show all the results returned by a sql query?

    Hi guys,
    I need your help.
    Let's say I have one table: TableA. Fields of TableA are aleg, anon, apes. The following sentence can return, in general, several rows: select anon from TableA where aleg = somevalue. I'd like to show the result of column anon but no luck. If I try to show the results in a TextArea and the origin is an sql query only shows the first row value. I tried Show as: show as text (based in PLSQL) and coding an anonymous plsql block as
    DECLARE
    v_anon TableA.anon%TYPE;
    CURSOR v_cur IS
         select anon from TableA where aleg = somevalue;
    BEGIN
    OPEN v_cur;
    LOOP
    FETCH v_cur INTO v_anon;
    EXIT WHEN v_cur%NOTFOUND;
    :FIELD_IN_FORM := v_anon;
    END LOOP;
    CLOSE v_cur;
    END;
    but in this case it's not shown any result.
    So the first question is what kind of field should I use to show the result. And the second one is what can I do to being able to show all the results returned by the query (provided that is more than one single row).
    regards

    Hi Denes,
    Just starting with apex. I think I know how to show the results in a report region. I've simplified the posted question.
    A more detailed question would be: Suppose you have a region where you have put several text areas to accommodate the result of a multi-column query (lets say for TableA) that only returns one row, each column value returned put in a different text area. Also you want to show the values of other fields in TableB that depends on some value just retrieved from TableA and that you want all values retrieved (from TableA and the linked TableB) to be show in the same region. Is that possible? If yes, how?
    Thank you in advance

  • JSP Servlet and convert the result set of an SQL Query To XML file

    Hi all
    I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
    thisis my servlet which will call the jsp page and the jsp just behind it.
    //this is the servlet
    import java.io.*;
    import java.lang.reflect.Array;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    public *class *Campaign *extends *HttpServlet
    *private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
    *private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
    *private* DataSource _dataSource;
    *public* *void* setDataSource(DataSource dataSource)
    _dataSource = dataSource;
    *public* DataSource getDataSource()
    *return* _dataSource;
    *public* *void* init()
    *throws* ServletException
    *if* (_dataSource == *null*) {
    *try* {
    Context env = (Context) *new* InitialContext().lookup("java:comp/env");
    _dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
    *if* (_dataSource == *null*)
    *throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
    } *catch* (NamingException e) {
    *throw* *new* ServletException(e);
    protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    Connection conn = *null*;
    *try* {
    conn = getDataSource().getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
    // out.println("Le r&eacute;sultat :<br>");
    ArrayList <String> Lescomments= *new* ArrayList<String>();
    ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
    ArrayList <String> Lesnoms = *new* ArrayList <String>();
    *while* (rs.next()) {
    Lescomments.add(rs.getString("comments"));
    request.setAttribute("comments",Lescomments);
    Lesidentifiant.add(rs.getString("post_id"));
    request.setAttribute("id",Lesidentifiant);
    Lesnoms.add(rs.getString("postname"));
    request.setAttribute("nom",Lesnoms);
    rs.close();
    stmt.close();
    *catch* (SQLException e) {
    *finally* {
    *try* {
    *if* (conn != *null*)
    conn.close();
    *catch* (SQLException e) {
    // les param&egrave;tres sont corrects - on envoie la page r&eacute;ponse
    getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
    }///end of servlet
    }///this is the jsp page called
    <%@ page import="java.util.ArrayList" %>
    <%
    // on r&eacute;cup&egrave;re les donn&eacute;es
    ArrayList nom=(ArrayList)request.getAttribute("nom");
    ArrayList id=(ArrayList)request.getAttribute("id");
    ArrayList comments=(ArrayList) request.getAttribute("comments");
    %>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    Liste des campagnes here i will create the xml file the problem is to display all rows
    <hr>
    <table>
    <tr>
    </tr>
    <tr>
    <td>Comment</td>
    <td>
    <%
    for( int i=0;i<comments.size();i++){
    out.print("<li>" + (String) comments.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>nom</td>
    <td>
    <%
    for( int i=0;i<nom.size();i++){
    out.print("<li>" + (String) nom.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>id</td>
    <td>
    <%
    for( int i=0;i<id.size();i++){
    out.print("<li>" + (String) id.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    </table>
    </body>
    </html>
    This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (*char*)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
    //outputFile.createNewFile();
    FileWriter outfile = *new* FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
    // Define connection string and make a connection to database
    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
    Statement stat = conn.createStatement();
    // Create a recordset
    ResultSet rset = stat.executeQuery("Select * From posts");
    // Expecting at least one record
    *if*( !rset.next() ) {
    *throw* *new* IllegalArgumentException("No data found for the posts table");
    outfile.write("<Table>"+cLf);
    // Parse our recordset
    // Parse our recordset
    *while*(rset.next()) {
    outfile.write("<posts>"+cLf);
    outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
    outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
    outfile.write("</posts>"+cLf);
    outfile.write("</Table>"+cLf);
    // Everything must be closed
    rset.close();
    stat.close();
    conn.close();
    outfile.close();
    catch( Exception er ) {
    %>

    Please state your problem that you are having more clearly so we can help.
    I looked at your code I here are a few things you might consider:
    It looks like you are putting freely typed-in comments from end-users into an xml document.
    The problem with this is that the user may enter characters in his text that have special meaning
    to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
    You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
    You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
    if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
    When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
    and re-displayed correctly.
    Also, it looks like you are putting business logic in your JSP page (creating an xml file).
    The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client.

  • How do i put the results from a calculation as the offset value

    hi .. i am trying to set the value of the mask offset from the results i get from a calculation.
    this is what i am trying to do
    i want to get a ROI from an image, so i used thresholding to separate it form the background
    then i find the centroid of the image. i then create a mask a little
    larger than the ROI to get rid of the background in an unthresholded
    image but the position of the mask is at origin(0,0)
    i need the centroid of the mask to be the same as the ROI. so i
    subtract the x and y values of the ROI centroid with the centroid of
    the mask to get the offset.  which is done manually. but i want to
    do it for ROIs in different positions, so i want to get the value of
    the subtraction staight into the VI .. how can i do that..?? i tried
    wiring the value of subtraction into the input of the "set offset" node
    but it does not work .. can anyone help me ??thanks very much

    i managed to get it done...i did not know how about the cluster to element function .. could you comment on my program?
     i'm trying to construct a sign language translator.  for the
    signing. i am using yellow colored gloves with colored finger tips. the
    yellow region is to help me detect the position of the gloves during
    thresholding.
    1st of all .. i do thresholding to separate the ROI from the
    background.. then i put a bouding box around the region of interest. is
    there any better and easier way to do this??
    could anyone point me in the right direction ?
     i am very new to LV and image processing. i always have problem
    using some functions especially when it requires lots of settings.
    sometimes the help file does no help much ..
    my next problem after creating the bounding box is how do i extract
    only the colors from the image? i tried color thresholding but the
    result is gray scale. how do i extract only the yellow region of the
    gloves and the finger tips to be further processed? in MATLAB , color
    segmentation is used.. but i can't figure how it works in LV .. please
    help me .. thanx
    Attachments:
    color threshold_andreas_centroid_mask.vi ‏263 KB

  • Putting the result of scheduler to a local directory

    We have BI Publisher running on a Solaris box.
    Our interest is to have the result(csv file) of a an already designed report in BI Publisher to automatically be put to a local directory on a local directory every time the schedule runs.
    I have gone over the bursting and splitting guides in my reach but i have not got a solution for outputting the complete result of the report(as a whole) to a specified directory. Most of the guides split the designed reports by a KEY on the dataset result and deliver the results in different files as specified by the key.
    My interest however is not to split the result of the Dataset in any way, but rather output the Dataset query result as a whole every time the schedule runs.
    Please advise on the possibility of this.

    I would re-post to the Flex Data Services forum.

  • Shouldn't using WITH return the same results as if you'd put the results in a table first?

    First off, here's my version info:
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE 11.1.0.7.0 Production
    TNS for HPUX: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    I just reread the documentation again on the subquery factoring clause of SELECT statement, and I didn't see any restrictions that would apply.
    Can someone help me understand why I'm getting different results?  I'd like to be able to use the statement that creates MAT3, but for some reason it doesn't work.  However, when I break it up and store the last TMP subquery in a table (MAT1), I'm able to get the expected results in MAT2.
    Sorry if the example seems a little esoteric.  I was trying to put something together to help illustrate another problem, so it was convenient to use the same statements to illustrate this problem.
    drop table mat1;
    create table mat1 as
    with skus as (
      select level as sku_id
      from dual
      connect by level <= 1000
      tran_dates as (
      select to_date('20130731', 'yyyymmdd') + level as tran_date
      from dual
      connect by level <= 31
      sku_dates as (
      select s.sku_id,
      t.tran_date,
      case when dbms_random.value * 5 < 4
      then 0
      else 1
      end as has_changes,
      round(dbms_random.value * 10000, 2) as unit_cost
      from skus s
      inner join tran_dates t
      on 1 = 1
    select d.sku_id,
      d.tran_date,
      d.unit_cost
      from sku_dates d
      where d.has_changes = 1
    drop table mat2;
    create table mat2 as
    select m.sku_id,
      m.tran_date,
      m.unit_cost,
      min(m.tran_date) over (partition by m.sku_id order by m.tran_date rows between 1 following and 1 following) as next_tran_date
      from mat1 m
    drop table mat3;
    create table mat3 as
    with skus as (
      select level as sku_id
      from dual
      connect by level <= 1000
      tran_dates as (
      select to_date('20130731', 'yyyymmdd') + level as tran_date
      from dual
      connect by level <= 31
      sku_dates as (
      select s.sku_id,
      t.tran_date,
      case when dbms_random.value * 5 < 4
      then 0
      else 1
      end as has_changes,
      round(dbms_random.value * 10000, 2) as unit_cost
      from skus s
      inner join tran_dates t
      on 1 = 1
      tmp as (
      select d.sku_id,
      d.tran_date,
      d.unit_cost
      from sku_dates d
      where d.has_changes = 1
    select m.sku_id,
      m.tran_date,
      m.unit_cost,
      min(m.tran_date) over (partition by m.sku_id order by m.tran_date rows between 1 following and 1 following) as next_tran_date
      from tmp m
    select count(*) from mat2;
    select count(*) from mat3;
      from tmp m
    select count(*) from mat2;
    select count(*) from mat3;
    select count(*) from mat2;
      COUNT(*)
         31000
    Executed in 0.046 seconds
    select count(*) from mat3;
      COUNT(*)
             0
    Executed in 0.031 seconds

    I think there's something else going on.
    I made the change you suggested, with a slight modification to retain the same functionality of flagging ~80% of the rows as not having changes.  I then copied that section of my script - included below - and pasted it into my session twice.  Unfortunately, I got different results each time.  I have had a number of strange problems when using the WITH clause, which is one of the reasons I jumped at posting something here when I encountered it again in this context.
    Can you help me understand why this would happen?
    drop table mat3;
    create table mat3 as
    with skus as (
      select level as sku_id
      from dual
      connect by level <= 1000
      tran_dates as (
      select to_date('20130731', 'yyyymmdd') + level as tran_date
      from dual
      connect by level <= 31
      sku_dates as (
      select s.sku_id,
      t.tran_date,
      case when dbms_random.value(1,100) * 5 < 400
      then 0
      else 1
      end as has_changes,
      round(dbms_random.value * 10000, 2) as unit_cost
      from skus s
      inner join tran_dates t
      on 1 = 1
      tmp as (
      select d.sku_id,
      d.tran_date,
      d.unit_cost
      from sku_dates d
      where d.has_changes = 1
    select m.sku_id,
      m.tran_date,
      m.unit_cost,
      min(m.tran_date) over (partition by m.sku_id order by m.tran_date rows between 1 following and 1 following) as next_tran_date
      from tmp m
    select count(*) from mat2;
    select count(*) from mat3;
    152249 < mattk > drop table mat3;
    Table dropped
    Executed in 0.016 seconds
    152249 < mattk > create table mat3 as
                             2  with skus as (
                             3   select level as sku_id
                             4   from dual
                             5   connect by level <= 1000
                             6   ),
                             7   tran_dates as (
                             8   select to_date('20130731', 'yyyymmdd') + level as tran_date
                             9   from dual
                            10   connect by level <= 31
                            11   ),
                            12   sku_dates as (
                            13   select s.sku_id,
                            14   t.tran_date,
                            15   case when dbms_random.value(1,100) * 5 < 400
                            16   then 0
                            17   else 1
                            18   end as has_changes,
                            19   round(dbms_random.value * 10000, 2) as unit_cost
                            20   from skus s
                            21   inner join tran_dates t
                            22   on 1 = 1
                            23   ),
                            24   tmp as (
                            25   select d.sku_id,
                            26   d.tran_date,
                            27   d.unit_cost
                            28   from sku_dates d
                            29   where d.has_changes = 1
                            30   )
                            31  select m.sku_id,
                            32   m.tran_date,
                            33   m.unit_cost,
                            34   min(m.tran_date) over (partition by m.sku_id order by m.tran_date rows between 1 following and 1 following) as next_tran_date
                            35   from tmp m
                            36  ;
    Table created
    Executed in 0.53 seconds
    152250 < mattk > select count(*) from mat2;
      COUNT(*)
             0
    Executed in 0.047 seconds
    152250 < mattk > select count(*) from mat3;
      COUNT(*)
         31000
    Executed in 0.047 seconds
    152250 < mattk >
    152251 < mattk > drop table mat3;
    Table dropped
    Executed in 0.016 seconds
    152252 < mattk > create table mat3 as
                             2  with skus as (
                             3   select level as sku_id
                             4   from dual
                             5   connect by level <= 1000
                             6   ),
                             7   tran_dates as (
                             8   select to_date('20130731', 'yyyymmdd') + level as tran_date
                             9   from dual
                            10   connect by level <= 31
                            11   ),
                            12   sku_dates as (
                            13   select s.sku_id,
                            14   t.tran_date,
                            15   case when dbms_random.value(1,100) * 5 < 400
                            16   then 0
                            17   else 1
                            18   end as has_changes,
                            19   round(dbms_random.value * 10000, 2) as unit_cost
                            20   from skus s
                            21   inner join tran_dates t
                            22   on 1 = 1
                            23   ),
                            24   tmp as (
                            25   select d.sku_id,
                            26   d.tran_date,
                            27   d.unit_cost
                            28   from sku_dates d
                            29   where d.has_changes = 1
                            30   )
                            31  select m.sku_id,
                            32   m.tran_date,
                            33   m.unit_cost,
                            34   min(m.tran_date) over (partition by m.sku_id order by m.tran_date rows between 1 following and 1 following) as next_tran_date
                            35   from tmp m
                            36  ;
    Table created
    Executed in 0.078 seconds
    152252 < mattk > select count(*) from mat2;
      COUNT(*)
             0
    Executed in 0.031 seconds
    152252 < mattk > select count(*) from mat3;
      COUNT(*)
             0
    Executed in 0.047 seconds

  • Using the result of string_to_table in SQL

    Hi,
    Apologies if this has already been answered - I couldn't seem to get the right mix of search terms to find what I was looking for.
    I'd like to know if there is a way to use the output or APEX_UTIL.string_to_table directly in SQL without any extra coding (I know I could create VARCHAR2 table type and CAST that to a table - essentially I'm wondering if this has already been done for you or not with APEX).
    So the end query would be something like:
    UPDATE my_table
       SET column_a = 12345
    WHERE my_id_column IN (SELECT column_value FROM TABLE(APEX_UTIL.string_to_table(:P1_MY_MULTISELECTLIST)));Regards,
    Gareth.

    Thanks guys,
    Both (obviously) spot on and which was the confirmation I was expecting.
    Denes' example was virtually identical to what I'd already come up with (probably cribbed from the same source! ;o)
    Andy with regards to the LIKE method this would have worked as well although (initially) I was concerned about the overhead of having to do a TO_CHAR for each row in the 'real' table - in my case they are numbers and not strings, but then I neglected to mention that in the original post so you couldn't have known that. It's also probably a fairly moot point as I have to send it through a function anyway only way to know which is best for a given situation is to test. My gut feel is that for relatively small number of rows there will be no difference/a slight edge towards a TO_CHAR and using LIKE but as the table volumes go up the in list idea might be best - don't quote me on that though!
    For what it's worth, my example is below, but it is essentially the same as Denes's/Tom Kyte's functions.
    CREATE OR REPLACE TYPE my_arr_t AS TABLE OF NUMBER(15, 0);
    CREATE OR REPLACE FUNCTION my_in_list(
       p_string   IN   VARCHAR2
       RETURN my_arr_t AS
       l_string   VARCHAR2(32767) DEFAULT p_string || ':';
       l_data     my_arr_t        := my_arr_t();
       n          NUMBER;
    BEGIN
       LOOP
          EXIT WHEN l_string IS NULL;
          n := INSTR(l_string, ':');
          l_data.EXTEND;
          l_data(l_data.COUNT) := TO_NUMBER(TRIM(SUBSTR(l_string, 1, n - 1)));
          l_string := SUBSTR(l_string, n + 1);
       END LOOP;
       RETURN l_data;
    END;
    SELECT *
      FROM TABLE(CAST(my_in_list('1:2:3:4:5:6:7:8:9:10') AS my_arr_t));Thanks both for the speedy replies.
    G.

  • Multiply numbers from 2 textFields, put the result into label.

            int minute;
            int cate;
            cate = [cateSunt.text intValue];
            minute = [minuteLabel.text intValue];
            int rezultat = cate * minute;
            NSString *result = [NSString stringWithFormat:@"%d", rezultat];
            [minuteLabel setText:result];
    I wrote the code above, but every time i press the button to run this code, the label (minuteLabel) changes into 0
    Thanks!

    Print out the values for cate and minute using NSLog.  I'm betting one or both = 0.

  • How to assign the result value of a sql stmt to a variable in sql*plus

    e.g.
    var v_date
    var v_test :=select hour from tablename where date=v_date

    but this piece of code doesn't work:
    var in_year number
    var start_date varchar2(30)
    var mar_2nd_sun date
    accept in_year number prompt 'Enter the year of interest>'
    execute :start_date := '01-mar-' || &&in_year
    print start_date
    select next_day(:start_date,'sunday')+7 into :mar_2nd_sun from dual;
    print mar_2nd_sun
    delete from &&table_name where tdate=:mar_2nd_sun and hour=1;
    Error:
    old 1: delete from &&table_name where tdate=:mar_2nd_sun and hour=1
    new 1: delete from tbl_datehour_test where tdate=:mar_2nd_sun and hour=1
    SP2-0552: Bind variable "MAR_2ND_SUN" not declared.

  • Where to put the sql

    Hi,
    When I develop a Java software which gets data from the user (for example a Web page) and use them for performing and put the result into the database, according to you is it almost always smarter calling an Oracle stored procedure or a package making the task or can it be usefull to put the logics-sql inside the Java code? For me it's always better to develop a strored procedure to be called, but I'd like to listen to your experience.
    Thanks!

    If the Java code is to run against a variety of different database products, then it is limited to the lowest common denominator between these products - the basic SQL language.
    And unfortunately, such code will use the various database products non-optimally. SQL language implementations differ. Analytical SQL functions available in one product will be different or even non-existent in another.
    But in this case, the Java code has little choice - and need to use bare bones SQL.
    Usually this is only a problem for ISVs that are developing commercial client products. For most others, we have a single database product as the strategic product for the selected IT architecture.
    So in this case it makes sense to use and leverage all the features of that database products. Enabling the Java code to optimally use the database. Enable the database to perform and scale.
    In the case of Oracle, that typically means not having Java developers code SQL at all. Not because they are SQL/Oracle idiots (which can be argued). But because of providing a formal and abstract data interface allows far greater flexibility, maintainability and usability.
    It enables you to to deal with SQL and SQL related performance inside this interface, without having to touch and recompile a single byte of Java client code.
    It enables you to deal with database structure changes via this interface, without having to touch and recompile a single byte of Java client code.
    So it makes a LOT of sense to create and use such an interface - not just for Java clients, but all clients. Allowing all clients to share the same interface and be subject to the same validation and business rules in a coherent and consistent fashion.
    In Oracle, this interface will be written using PL/SQL packages - and will typically return ref cursors to the clients.

Maybe you are looking for

  • Lid closing does not suspend after update today

    ...and again: after todays update lid close does not longer trigger suspending my t420s. The last times(!) the cure came always with another update. Please do it again It saves a lot of time. Thx ahead

  • Trust relation between mac server 2.2.1 (10.8 mountain lion) and windows server 2008 r2

    i have the following settings: windows 2008R2 domain server. mac server 2.2.1 mac client machines mac server machine is joined to Active Directory in windows 2008r2 without any problems. mac client machine is joined to mac server without any problem.

  • How do I purchase a IPhone at full price from the Apple Store.

    I have been a Verizon customer for over 10 years, and I currently have the unlimited data plan.  I was informed that if I upgrade my IPhone I would be required to switch to another Data plan (because the unlimited data plan is no longer offered).  I

  • Quick time error report

    Hi, When i try to open my iTunes, an error message pops up... these are the details: AppName: itunes.exe AppVer: 9.0.2.25 ModName: ntdll.dll ModVer: 5.1.2600.5755 Offset: 0001b21a Then i tried to open up my quicktime, and i recieved another error mes

  • Payment of iTunes

    how I can remove my payment of iTunes?