Returning a SQL query result (resultset)

Hello,
I would like to return records from a SQL query but i can't return the resultset because the connection is already close.
How can i return the records from a query if it contain different types (int, string)?
I've been told to create another class which will hold the different variables and to return an instance of that class,
how can i do it?
Thanks,
Raz

what do you mean by "Whatsit"?
i have this code:
public class BestSeller {
...some functions...
public void SearchNAME (BestSeller DB, String table,String name) {
          DB.connect();
          try{
               Statement stmt = con.createStatement();
               resultSet = stmt.executeQuery("Select * from "+table+" where name like'"+name+"'");
               //CachedRowSet rset = new CachedRowSet();
               while (DB.resultSet.next()) {
                    System.out.println(DB.resultSet.getInt("ID")+" is "+DB.resultSet.getString("name")+", "+...+", "+DB.resultSet.getString("quantity")+", "+DB.resultSet.getString("delivery_time"));
               stmt.close();
               con.close();
          catch (Exception err) {
               System.out.println("ERROR: " + err);
     }I didn't put the Connect function in here, but it works and i get the records printed to the screen.
I want to return all of the records (usually more then 1).
Can you tell me how can i implement your code to my case?
Thanks for the quick reply.
Edited by: raz27 on Aug 5, 2008 2:20 PM

Similar Messages

  • Set Text Item To SQL Query Result

    I am trying to set a text item to a SQL query result. Something like the following:
    (I am trying to accomplish this in the SOURCE portion, set to 'SQL Query' source type, of the text item properties)
    SELECT empno FROM emp WHERE empno = :SEARCH_EMPNO;
    This only displays as the literal text when the application renders and not the value from the SQL query.
    I apologize if this has already been posted but I could not find what I am looking for. I have seen posts that reference a pre-region computation but do not know the exact steps to accomplish the results I want.
    Thanks in advance for anyone's time to help me with my issue.
    Kyle

    Scott,
    The literal that displayed (I have fixed it) was the actual SQL statement: SELECT empno FROM emp WHERE empno = :SEARCH_EMPNO;
    I have resolved the issue, using SQL Query as the "Source Type" and Always, replacing any existing value in session state as the "Source Used" for the properties of the item.
    What I was trying to accomplish is a search text item that would return the data for that record in a table into other text items, for each column in that record, for update; based on the search text item as a unique SQL query search for that record.
    Thank you for your quick reply!
    Kyle

  • SQL Query results to CSV as two worksheets

    I'm trying to take two SQL queries and get the results sent to a CSV file on two worksheets.  Looking online I have not found a solid example of using the Excel ComObject to create a CSV then add a new worksheet to the CSV file.  An added bonus
    would be using AutoFit on the columns so everything is easily visible.
    Code found online got me the following script which does work, however it takes 12 minutes to pipe the SQL queries to Excel.  Switching to a CSV and the script executes in 5 seconds.
    This is another nice to have, I was also looking the best way to look at the results (only 1 column) and depending on the length of the data, insert what Excel would call a Cell thereby shifting cells RIGHT but so far have found no clear examples of how
    to accomplish that.  My guess would be modifying my SQL queries but I've posted a question on StackOverFlow and someone suggested modifying the PowerShell Table created from the SQL dataset.Tables
    Code:
    $docs = "C:\Scripts\Output.xlsx"
    If (Test-Path $docs){Remove-Item $docs}
    Function Run-Query {
    param([string[]]$queries,[string[]]$sheetnames)
    ## - Create an Excel Application instance:
    $xlsObj = New-Object -ComObject Excel.Application
    $xlsObj.DisplayAlerts = $false
    $xlsWb = $xlsobj.Workbooks.Add(1)
    ## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
    $xlsObj.Visible = 0
    $time = 2
    for ($i = 0; $i -lt $queries.Count; $i++){
    $percentage = $i / $time
    $remaining = New-TimeSpan -Seconds ($time - $i)
    $message = "{0:p0} complete" -f $percentage, $remaining
    Write-Progress -Activity "Creating Daily Reboot Spreadsheet" -status $message -PercentComplete ($percentage * 100)
    $query = $queries[$i]
    $sheetname = $sheetnames[$i]
    $xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Count))
    $xlsSh.Name = $sheetname
    ### SQL query results sent to Excel
    $SQLServer = 'ServerName'
    $Database = 'DataBase'
    ## - Connect to SQL Server using non-SMO class 'System.Data':
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $query
    $SqlCmd.Connection = $SqlConnection
    ## - Extract and build the SQL data object '$Table2':
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
    $Table1 = $DataSet.Tables["Table"]
    ## - Build the Excel column heading:
    [Array] $getColumnNames = $Table1.Columns | SELECT ColumnName
    ## - Build column header:
    [Int] $RowHeader = 1
    foreach ($ColH in $getColumnNames)
    $xlsSh.Cells.item(1, $RowHeader).font.bold = $true
    $xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
    $RowHeader++
    ## - Adding the data start in row 2 column 1:
    [Int] $rowData = 2
    [Int] $colData = 1
    foreach ($rec in $Table1.Rows)
    foreach ($Coln in $getColumnNames)
    ## - Next line convert cell to be text only:
    $xlsSh.Cells.NumberFormat = "@"
    ## - Populating columns:
    $xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
    $ColData++
    $rowData++; $ColData = 1
    ## - Adjusting columns in the Excel sheet:
    $xlsRng = $xlsSH.usedRange
    [void] $xlsRng.EntireColumn.AutoFit()
    }#End For loop.
    #Delete unwanted Sheet1.
    $xlsWb.Sheets.Item('Sheet1').Delete()
    #Set Monday to Active Sheet upon opening Workbook.
    $xlsWb.Sheets.Item('Cert').Activate()
    ## ---------- Saving file and Terminating Excel Application ---------- ##
    $xlsFile = "C:\Scripts\Output.xlsx"
    [void] $xlsObj.ActiveWorkbook.SaveAs($xlsFile)
    $xlsObj.Quit()
    ## - End of Script - ##
    start-sleep 2
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
    [gc]::collect() | Out-Null
    [gc]::WaitForPendingFinalizers() | Out-Null
    }#End Function
    $queries = @()
    $queries += "Query1"
    $queries += "Query2"
    $sheetnames = @('Cert','Prod')
    Run-Query -queries $queries -sheetnames $sheetnames

    Here's what I ended up with that accomplishes my goal.  I learned it's not possible to create a CSV with two worksheets since Excel will allow this but the CSV cannot be saved with the second worksheet.  Instead, I create two CSV files then merge
    them into one Excel workbook, one CSV per worksheet.  In my case, this happens in 5 seconds.  There is one thing which must be mentioned, I've seen this script fail the first time it is run but will successfully run the second time.
    Also note, after much trial and error, this code correctly cleans up the Excel ComObject!!  -Thanks go to JRV.
    $docs = "D:\Scripts\MonthlyReboots.xlsx"
    IF (Test-Path $docs){Remove-Item $docs}
    $csv1 = "D:\Scripts\Cert.csv"
    IF (Test-Path $csv1){Remove-Item $csv1}
    $csv2 = "D:\Scripts\Prod.csv"
    IF (Test-Path $csv2){Remove-Item $csv2}
    Function Run-Query {
    param([string[]]$queries,[string[]]$sheetnames,[string[]]$filenames)
    Begin{
    $SQLServer = 'ServerName'
    $Database = 'DataBase'
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = 0
    $dest = $Excel.Workbooks.Add(1)
    }#End Begin
    Process{
    For($i = 0; $i -lt $queries.Count; $i++){
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $queries[$i]
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "D:\Scripts\$($sheetnames[$i]).csv" -Force
    }#end for loop.
    }#End Process
    End{
    $SqlConnection.Close()
    #Excel magic test!
    For($i = 0; $i -lt $queries.Count; $i++){
    $loopy = (Resolve-Path -Path $filenames[$i]).ProviderPath
    $Book = $Excel.Workbooks.Open($loopy)
    $next = $Excel.workbooks.Open($loopy)
    $next.ActiveSheet.Move($dest.ActiveSheet)
    $xlsRng = $dest.ActiveSheet.UsedRange
    $xlsRng.EntireColumn.AutoFit() | Out-Null
    $dest.sheets.item('Sheet1').Delete()
    $xlsFile = "D:\Scripts\MonthlyReboots.xlsx"
    [void] $Excel.ActiveWorkbook.SaveAs($xlsFile)
    $Excel.Quit()
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($next)) {'cleanup xlsSh'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Book)) {'cleanup xlsWb'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)) {'cleanup xlsObj'}
    [gc]::collect() | Out-Null
    [gc]::WaitForPendingFinalizers() | Out-Null
    }#End end block.
    }#End function run-query.
    $queries = @()
    $queries += @'
    Select * from table1
    $queries += @'
    Select * from table2
    $sheetnames = @("Cert","Prod")
    $filenames = @("D:\Scripts\Prod.csv","D:\Scripts\Cert.csv")
    Run-Query -queries $queries -sheetnames $sheetnames -filenames $filenames
    Start-Sleep -Milliseconds 50
    Invoke-Item D:\Scripts\MonthlyReboots.xlsx

  • Analyze: PL/SQL function body returning an SQL query

    I need to obtain the final SQL returned by the PL/SQL function.
    I will be using this final SQL in a procedure.
    Please provide some advise on how to obtain the SQL. I have already looked in the DBMS_SQL package but I am not sure if that is the right place to look into.
    Regards,
    Sumit

    I am trying to modify the export_to_excel package from Denes kubicek to provide me an excel from PL/SQL function body returning an SQL query.
    Here is the simplified PLSQL code in the region source.
    declare
    l2 varchar2(2000) null;
    begin
    l2:= 'Select NAME,ORIGINATED,OWNER,ORIGINATOR,';
    l2:= l2 || 'DESIGNATED_UNIT,SOURCE,';
    l2:= l2 || 'REFERENCE';
    l2:= l2 || ' from MV_DETAILED_DATA';
    return l2;
    end;
    I would like to get the SQL returned from this PLSQL and use it in a procedure to get the Excel.
    As you mentioned earlier "copy the generated query string into an application item". [ +In the PL/SQL function body returning an SQL query, copy the generated query string into an application item. The app item value can then be passed as a parameter value to the procedure+ ]
    I do not know how to dynamically excute this PLSQL in the region source and obtain the returned value in my procedure.
    Best Regard,
    Sumit.

  • How to return SQL query results as resultset

    I am developing a site in ASP to support back end as oracle or SQL server.
    In SQL Server, from stored procedure it is possible to return resultset by writing sql query in procedure using input parameters as filters (where condition).
    Is there a way to return a resultset from oracle procedures or functions.

    http://asktom.oracle.com/~tkyte/ResultSets/index.html
    In 9i or above you no longer need to define your own weak ref cursor type in a package spec, you can use the built-in SYS_REFCURSOR.

  • Invoking a process to return a SQL query as XML results in empty XML tag (but testing the SQL works)

    I have a process that runs a SQL query and returns the results as XML.  When I test the query in the Process Properties tab in Workbench it appears to execute just fine.  I can also test the XML information and see that the results are coming back correctly.  But when I invoke the process I get an emtpy XML tag with no results.  Recording the invocation and playing back the recording doesn't tell me anything useful.  Has anyone ever seen this issue before?  I don't understand why everything within the process seems to bring back results just fine but invoking it returns nothing.

    Unfortunately I am not the admin for our LiveCycle instance and do not have access to the server logs (long story).  I also am not authorized to share any LCA files for this project.  Thanks though.

  • How to send SQL query results to XML ?

    Hey Guys, I am querying a DB with huge amount of traffic. A user select a particular lot and then details of the lot will be displayed in the following page. My concern here is that it takes really LONG to retrieve back the results coz it has to requiry in the following JSP page.
    I was told to use XML to retrieve the dataset and store it. Hence, in the following query it will re-query only from the recordsets in the XML file (...Logically, should be faster rite ? ). Hence, how do parse my recordsets retrieved from the SQL query to an XML file ?
    Any sort of suggestion , help, reference would be deeply appreciated ..Thanks !

    <HTML>
    <BODY>
    <H1>Manufacturing Summary beta </H1><BR>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.lang.*" %>
    <%@ page import="java.text.*" %>
    <jsp:include page="/index.html" flush="true"/>
    <P><B>Returned result<B><BR>
    <B>Query String :</B><%=request.getParameter("date") %>
    <TABLE BORDER=1 cellpadding=0 cellspacing=0>
    <%!
    static double roundDouble(double toBeRounded, int fractionDigits)
    NumberFormat format = NumberFormat.getInstance();
    format.setMaximumFractionDigits(fractionDigits);
    String tempDouble = format.format(toBeRounded);
    return Double.parseDouble(tempDouble);
    %>
    <%
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@klmomnidb:1521:
    OMNIDB","omni","omni");
    Statement stmt = null;
    ResultSet rset = null;
    String S_date = new String();
    String temp = new String();
    String lot_id = new String();
    String result = new String();
    String SQL_String = new String();
    double yield;
    int bad_cnt;
    S_date = request.getParameter("date");
    lot_id = request.getParameter("lot_id");
    temp = request.getParameter("TST_TEMP");
    SQL_String = "SELECT LOT_ID, FLOW_ID, TST_TEMP, MODE_COD, RTST_COD, PART_CNT, GO
    OD_CNT, OPER_NAM, JOB_REV, PROC_ID, START_T, FACIL_ID, TSTR_TYP, NODE_NAM FROM L
    OT where START_T > TO_DATE('"+ S_date + "','MM/DD/YYYY') AND TST_TEMP <='" + tem
    p+"' order by START_T";
    out.println(SQL_String);
    stmt = conn.createStatement();
    rset = stmt.executeQuery (SQL_String);
    out.println("<TR>");
    out.println("<TD> Select Lot(s)</TD>");
    out.println("<TD>Flow </TD>");
    out.println("<TD>Temp </TD>");
    out.println("<TD>Test Mode </TD>");
    out.println("<TD>Retest</TD>");
    out.println("<TD>Total </TD>");
    out.println("<TD>Good</TD>");
    out.println("<TD>Bad</TD>");
    out.println("<TD>Yield </TD>");
    out.println("<TD>UserID</TD>");
    out.println("<TD>Program</TD>");
    out.println("<TD>Mask</TD>");
    out.println("<TD>Start Time </TD>");
    out.println("<TD>Loc </TD>");
    out.println("<TD>Tester</TD>");
    out.println("<TD>System </TD>");
    out.println("</TR>");
    if (! rset.next()) {
    result ="No records found matching seach criteria.";
    while (rset.next()) {
    bad_cnt = Integer.parseInt(rset.getString(6)) - Integer.parseInt(rset.getString(
    7));
    yield = (Double.parseDouble(rset.getString(7)) / Double.parseDouble(rset.getStri
    ng(6))) * 100;
    result= "<TR>";
    result = result + "<TD><a href=coolpage.jsp?LOT_ID=" + rset.getString(1)+ ">" +
    rset.getString(1) + "</A></TD>";
    result = result + "<TD>" + rset.getString(2) + "</TD>";
    result = result + "<TD>" + rset.getString(3) + "</TD>";
    result = result + "<TD>" + rset.getString(4) + "</TD>";
    result = result + "<TD>" + rset.getString(5) + "</TD>";
    result = result + "<TD>" + rset.getString(6) + "</TD>";
    result = result + "<TD>" + rset.getString(7) + "</TD>";
    result = result + "<TD>" + bad_cnt + "</TD>";
    result = result + "<TD>" + roundDouble(yield,2) + "% </TD>";
    result = result + "<TD>" + rset.getString(8) + "</TD>";
    result = result + "<TD>" + rset.getString(9) + "</TD>";
    result = result + "<TD>" + rset.getString(10) + "</TD>";
    result = result + "<TD>" + rset.getString(11) + "</TD>";
    result = result + "<TD>" + rset.getString(12) + "</TD>";
    result = result + "<TD>" + rset.getString(13) + "</TD>";
    result = result + "<TD>" + rset.getString(14) + "</TD>";
    result = result + "</TR>"; %>
    <%=result%>
    <% }
    rset.close();
    stmt.close();
    conn.close();
    %>
    <%=result%>
    </TABLE>
    </BODY>
    </HTML>

  • How to get an sql query result to a textbox?

    i am working with jdk1.4 and office 2003.
    i need to run the following SQL Query: "SELECT max(BookId) as BookId FROM Books" where BookId is an autonumeric generated number obtained from the field autonumber in access 2003 database.
    now, the result of this must be placed in a textbox.
    does anyone knows how to do this?
    I ve tried this but nothing happens and niether any error comes
    st = con.createStatement ();     //Creating Statement Object.
    long bookNo;          //Use for Comparing the Book's Id.
    try {     //SELECT Query to Retrieved the Record.
    String q = "SELECT max(BookId) as BookId FROM Books";
    ResultSet rs = st.executeQuery (q);     //Executing the Query.
    bookNo = rs.getLong ("BookId");          //Storing the Record.
    bookNo =(bookNo+1);
    txtBookId.setText (""+bookNo);
    catch (SQLException sqlex) { }
    does anyone knows how to do this?????plz help me out.
    Thanks
    Aanchal

    Hi Aanchal,
    If an SQL error occurs now, you cannot see it in your code. You should do something with the exception you catch, e.g. printing it: sqlex.printStackTrace(), so that you can see if something goes wrong.
    For your number, you should move the cursor in the resultset to the first row - either by: calling first( ) or next ( ), then you can retrieve your booknumber.
    Best Regards,
    Martijn

  • SQL query to ResultSet

    I've been stuck on this little problem for a while: I'm trying to pass in two dates, startDate and endDate, which the user inputs, into a database query using the following SQL statements:
    String totalquantity =
    "SELECT SUM(quantity_) AS quantity " +
    "FROM FILLTABLE " +
    "WHERE time_ >= TO_DATE('startDate','mm/dd/yyyy') " +
    "AND time_ < TO_DATE('endDate','mm/dd/yyyy') " +
    After compiling gives me no error, I run the code and obtain an error in the following line, where i'm trying to assign the result of my query to ResultSet, and stops the program from running:
    ResultSet rs = stmt.executeQuery(totalquantity);
    Am I doing something wrong? can someone help? thanks!

    Hi!
    Compiler doesn't bring errors because the String is concatinated correctly and the argument to stmt.executeQuery() is a valid String so syntactically everything is fine. What the compiles doesn't know is that the String contains wrong sql-syntax. This gives you a runtime error while stmt.executeQuery(). Here your servlet receives an error from your databaseserver that complaint about the wring sql-syntax.
    This is the reason for compiling but not running so you will have to check your query string. But Sudha pointed you in the correct direction already so it should be no more problem.
    Thomas.

  • How do I query off a pl/sql funtion that returns an sql query in apex.

    I built a function that a returns a good sql query. I verified the out put of my function works when I manually entered into the SQL Commands.
    Is it possible to build a report off of this query. My attempt failed with the following error.
    failed to parse SQL query:
    ORA-00933: SQL command not properly ended
    I am sure the query generated is correct. Like I mentioned, I was able to use in the sql command succesfully.
    Thanks,
    Edited by: greich on Nov 21, 2008 10:55 AM

    This is the code for my function:
    create or replace function f_act_proj_sched (i_facility varchar2, i_date varchar2, i_shift varchar2)
    Return varchar2 is
    o_query Varchar2 (32000);
    BEGIN
    -- function that will return the query used in main application
    o_query := o_query || 'SELECT act_proj.DESTINATION,';
    o_query := o_query || ' act_proj.SHIPPING_DATE,';
    o_query := o_query || ' act_proj.SHIFT,';
    o_query := o_query || ' act_proj.JOB_CLASS_GROUPING,';
    o_query := o_query || ' act_proj."Actual Units",';
    o_query := o_query || ' act_proj."Projected Units",';
    o_query := o_query || ' act_proj."Actual Hours",';
    o_query := o_query || ' act_proj."Projected Hours",';
    o_query := o_query || ' NVL (sched."Sched_Hours", 0)';
    o_query := o_query || ' "Scheduled Hours"';
    o_query := o_query || ' From (SELECT P.DESTINATION,';
    o_query := o_query || ' P.SHIPPING_DATE,';
    o_query := o_query || ' P.JOB_CLASS_GROUPING,';
    o_query := o_query || ' P.SHIFT,';
    o_query := o_query || ' NVL (FACILITY_STATS.WORK_UNITS, 0) "Actual Units",';
    o_query := o_query || ' NVL (P.WORK_UNITS, 0) "Projected Units",';
    o_query := o_query || ' NVL (CASE FACILITY_STATS.JOB_CLASS_GROUPING';
    o_query := o_query || ' WHEN ''Backhaul''';
    o_query := o_query || ' THEN Facility_stats.work_units';
    o_query := o_query || ' / Goal_destination_shift.backhauler_goal';
    o_query := o_query || ' WHEN ''Selector''';
    o_query := o_query || ' THEN Facility_stats.work_units';
    o_query := o_query || ' / Goal_destination_shift.selector_goal';
    o_query := o_query || ' WHEN ''Common''';
    o_query := o_query || ' THEN Facility_stats.work_units';
    o_query := o_query || ' / Goal_destination_shift.backhauler_goal';
    o_query := o_query || ' WHEN ''Lift''';
    o_query := o_query || ' THEN Facility_stats.work_units';
    o_query := o_query || ' / Goal_destination_shift.forklift_goal';
    o_query := o_query || ' ELSE Facility_stats.work_units';
    o_query := o_query || ' END, 0) "Actual Hours",';
    o_query := o_query || ' CASE P.JOB_CLASS_GROUPING';
    o_query := o_query || ' WHEN ''Backhaul''';
    o_query := o_query || ' THEN P.work_units';
    o_query := o_query || ' / Goal_destination_shift.backhauler_goal';
    o_query := o_query || ' WHEN ''Selector''';
    o_query := o_query || ' THEN P.work_units';
    o_query := o_query || ' / Goal_destination_shift.selector_goal';
    o_query := o_query || ' WHEN ''Common''';
    o_query := o_query || ' THEN P.work_units';
    o_query := o_query || ' / Goal_destination_shift.backhauler_goal';
    o_query := o_query || ' WHEN ''Lift''';
    o_query := o_query || ' THEN P.work_units' ;
    o_query := o_query || ' / Goal_destination_shift.forklift_goal';
    o_query := o_query || ' ELSE P.work_units';
    o_query := o_query || ' END "Projected Hours"';
    o_query := o_query || ' FROM STAFFING.FACILITY_STATS,';
    o_query := o_query || ' STAFFING.FACILITY_STATS P,';
    o_query := o_query || ' STAFFING.GOAL_DESTINATION_SHIFT';
    o_query := o_query || ' WHERE (GOAL_DESTINATION_SHIFT.DESTINATION = P.DESTINATION)';
    o_query := o_query || ' AND (GOAL_DESTINATION_SHIFT.SHIFT_FLAG = P.SHIFT)';
    o_query := o_query || ' AND (FACILITY_STATS.DESTINATION(+) = P.DESTINATION)';
    o_query := o_query || ' AND (FACILITY_STATS.SHIPPING_DATE(+) = P.SHIPPING_DATE)';
    o_query := o_query || ' AND (FACILITY_STATS.JOB_CLASS_GROUPING(+) = P.JOB_CLASS_GROUPING)';
    o_query := o_query || ' AND (FACILITY_STATS.SHIFT(+) = P.SHIFT)';
    o_query := o_query || ' AND (P.PROJ_ACTUAL_FLAG = ''P'')';
    o_query := o_query || ' AND (FACILITY_STATS.PROJ_ACTUAL_FLAG(+) = ''A'')';
    o_query := o_query || ' AND P.DESTINATION = ' || i_facility;
    o_query := o_query || ' AND P.SHIPPING_DATE = ' || i_date;
    o_query := o_query || ' AND (case';
    o_query := o_query || ' when to_number(' || i_shift || ') != -1';
    o_query := o_query || ' Then P.SHIFT';
    o_query := o_query || ' Else 1';
    o_query := o_query || ' end =';
    o_query := o_query || ' case';
    o_query := o_query || ' when to_number(' || i_shift || ') != -1';
    o_query := o_query || ' Then to_number(' || i_shift || ')';
    o_query := o_query || ' Else 1';
    o_query := o_query || ' end)) act_proj,';
    o_query := o_query || ' (SELECT Destination,';
    o_query := o_query || ' schedule_date,';
    o_query := o_query || ' shift,';
    o_query := o_query || ' job_class_grouping,';
    o_query := o_query || ' SUM ("Sched_Hours") "Sched_Hours"';
    o_query := o_query || ' FROM (';
    -- Loop to create bucket query
    for idx in 1..20 Loop
    o_query := o_query || '(SELECT EMP_SCHEDULE.EMPLOYEE_ID,';
    o_query := o_query || ' EMP_SCHEDULE.SCHEDULE_DATE,';
    o_query := o_query || ' EMP_SCHEDULE.DESTINATION,';
    o_query := o_query || ' EMP_SCHEDULE.SHIFT, ';
    o_query := o_query || idx || ' "Bucket_number",';
    o_query := o_query || ' Bucket' || idx || '_class "bucket class",';
    o_query := o_query || ' JOB_CLASS_GROUPING,';
    o_query := o_query || ' NVL (EMP_SCHEDULE.BUCKET' || idx || '_SCHED_HRS, 0) "Sched_Hours"';
    o_query := o_query || ' FROM STAFFING.EMP_SCHEDULE,';
    o_query := o_query || '(SELECT DISTINCT FACILITY_CLASS_BUCKET.JOB_CLASS_GROUPING,';
    o_query := o_query || ' FACILITY_CLASS_BUCKET.DESTINATION';
    o_query := o_query || ' FROM STAFFING.FACILITY_CLASS_BUCKET';
    o_query := o_query || ' WHERE (FACILITY_CLASS_BUCKET.BUCKET_ID = ' || idx || ')) A';
    o_query := o_query || ' Where A.Destination = EMP_SCHEDULE.DESTINATION';
    o_query := o_query || ' and EMP_SCHEDULE.DESTINATION = ' || i_facility;
    o_query := o_query || ' and EMP_SCHEDULE.SCHEDULE_DATE = ' || i_date;
    o_query := o_query || ' AND (case';
    o_query := o_query || ' when to_number(' || i_shift || ') != -1';
    o_query := o_query || ' Then EMP_SCHEDULE.SHIFT';
    o_query := o_query || ' Else 1';
    o_query := o_query || ' end =';
    o_query := o_query || ' case';
    o_query := o_query || ' when to_number(' || i_shift || ') != -1';
    o_query := o_query || ' Then to_number(' || i_shift || ')';
    o_query := o_query || ' Else 1';
    o_query := o_query || ' end))';
    if idx < 20
    THEN
    o_query := o_query || ' UNION ';
    Else
    o_query := o_query || ')';
    End if;
    END Loop;
    o_query := o_query || ' GROUP BY Destination,';
    o_query := o_query || ' schedule_date,';
    o_query := o_query || ' shift,';
    o_query := o_query || ' job_class_grouping) Sched';
    o_query := o_query || ' WHERE (act_proj.DESTINATION = sched.DESTINATION(+))';
    o_query := o_query || ' AND (act_proj.SHIPPING_DATE = sched.SCHEDULE_DATE(+))';
    o_query := o_query || ' AND (act_proj.SHIFT = sched.SHIFT(+))';
    o_query := o_query || ' AND (act_proj.JOB_CLASS_GROUPING = sched.JOB_CLASS_GROUPING(+))';
    o_query := o_query || ' ORDER BY SHIFT,';
    o_query := o_query || ' job_class_grouping';
    Return (o_query);
    END;

  • Store SQL query results in db table

    Hi,
    I have a SQL query that produces a report table.
    Is it possible to automatically store the query results (or the report table) as a db table - without interrupting the current report building proces?
    Thanks,
    Dave
    Message was edited by:
    Dave Judge

    Hi Dave,
    You can also insert records into an existing table:
    INSERT INTO TABLEB (colA, colB, colC, etc) SELECT valA, valB, valC, etc FROM VIEWA WHERE etc etc
    This can be done during a page process that runs "Before Header" and you can base your report on the TABLEB. Obviously, you will need to maintain that table to ensure that it is only truncated where necessary, that one user doesn't try to access another user's data on that table and that each time your page is loaded it doesn't try to repopulate the table when you don't need it to.
    Another possiblity is to use a collection - which is user session based
    Andy

  • SQL Query Result with Random Sorting

    Hi Experts,
    My Oracle Version : Oracle9i
    I have three tables which are given below,
    Table Name:     check_team
    team_id      team_code
    100          A
    101          B
    102          C
    103          D
    Table Name:     check_product
    product_id     product_code
    1          XXX
    2          XYZ
    Table Name:     check_team_products
    tprod_id     tprod_team_id     tprod_product_id
    1          100          1
    2          100          2
    3          101          1
    4          101          2
    5          102          1
    6          102          2
    7          103          1
    8          103          2
    Required Output First Time:
    team_id   team_code   product_id   product_code
    100       A           1             XXX
    101       B           2             XYZ
    102       A           1             XXX
    103       B           2             XYZ
    Required Output Second Time:
    team_id   team_code   product_id   product_code
    100       B           2             XYZ
    101       A           1             XXX
    102       B           2             XYZ
    103       A           1             XXXI need the result as Required Output specified above and also the result has to be random too.. Can someone help me in writing a SQL Query to get results as that?
    Added Oracle Version

    So, is it something like this you want?
    SQL> ed
    Wrote file afiedt.buf
      1  with check_team as (select 100 as team_id, 'A' as team_code from dual union all
      2                      select 101, 'B' from dual union all
      3                      select 102, 'C' from dual union all
      4                      select 103, 'D' from dual)
      5      ,check_product as (select 1 as product_id, 'XXX' as product_code from dual union all
      6                         select 2, 'XYZ' from dual)
      7      ,check_team_products as (select 1 as tprod_id, 100 as tprod_team_id, 1 as tprod_product_id from dual union all
      8                               select 2, 100, 2 from dual union all
      9                               select 3, 101, 1 from dual union all
    10                               select 4, 101, 2 from dual union all
    11                               select 5, 102, 1 from dual union all
    12                               select 6, 102, 2 from dual union all
    13                               select 7, 103, 1 from dual union all
    14                               select 8, 103, 2 from dual)
    15  --
    16  -- end of test data
    17  --
    18  select team_id, team_code, product_id, product_code
    19  from (
    20        select t.team_id, t.team_code, p.product_id, p.product_code
    21              ,row_number() over (partition by team_id order by dbms_random.random()) as rn
    22        from check_team t join check_team_products tp on (tp.tprod_team_id = t.team_id)
    23                          join check_product p on (p.product_id = tp.tprod_product_id)
    24       )
    25* where rn = 1
    SQL> /
       TEAM_ID T PRODUCT_ID PRO
           100 A          2 XYZ
           101 B          1 XXX
           102 C          2 XYZ
           103 D          1 XXX
    SQL> /
       TEAM_ID T PRODUCT_ID PRO
           100 A          2 XYZ
           101 B          1 XXX
           102 C          2 XYZ
           103 D          1 XXX
    SQL> /
       TEAM_ID T PRODUCT_ID PRO
           100 A          1 XXX
           101 B          2 XYZ
           102 C          1 XXX
           103 D          1 XXX

  • Email SQL query results from powershell

    I currently have a script that I run every half hour which runs an sql query, and takes the results, and emails them to a group of users.  The script states how many faxes are in a faxmaker queue.  Now, the powers that be would like to add additional
    information, and I wanted to know how to include the additional information in my query. So, here is the script that is working.  I've changed some information to protect the innocent.
    $DATETIME = Get-Date -Format "MM-dd-yyyy [HH:mm:ss]";
    ##### CREATE A LOG FILE AND INSERT A LOG HEADING ;
    $LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME ;
    Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING ; 
    # get sql dbname  sample
    #email variables
    $EmailFrom = "[email protected]" ;
    $EmailTo = "My Email List" 
    $SqlServer = "MY-SQL-SERVER"
    $SqlCatalog = "FAXmakerArchive"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
    $SqlConnection.Open()
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = "SELECT count (DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT FROM
    FM_FAXIN fax WITH (NOLOCK) LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX WHERE (fax.RESULT LIKE '%SUCCESS%' OR (fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0)) AND
    ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0 AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK) WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION =
    3) AND fax.DATE >   '2013-09-25' "                                        
    $SqlCmd.Connection = $SqlConnection
    $NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
    $SqlConnection.Close()
    if( $NumberOfFlaInboundFaxes -gt 29)
    #Email Body
    $EmailBody = @"
    There are currently $NumberOfFlaInboundFaxes Faxes in the Florida Inbound Fax Queue (  )`n
    Please Log in and help clear the Queue.  Thank you. `n
    `n`n`n
    The people who recieved this email are: $EmailTo`n`n`n
    From ApexAdmin/SystemScheduler
    $EmailSubject = "There are " + $NumberOfFlaInboundFaxes + " faxes in the Inbound Florida Fax Queue. " + $DATETIME   ;
    #End of Email Body
    #send mail via gmail through powersehll
    $SMTPServer = "smtp.gmail.com" 
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
    $SMTPClient.EnableSsl = $true 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password"); 
    $SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
    Else
    Write-Host "NO ALERT  on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
    #Write-output "There are currently: " $NumberOfFlaInboundFaxes " Faxes in the Florida Fax Queue"
    Write-Host "There are currently "  $NumberOfFlaInboundFaxes  " Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
    Write-Host "SMTP Alert sent to " ( "$EmailTo" ).ToUpper() " on $DATETIME `n" -foreground 'DARKBLUE' -background 'WHITE' ;
    write-Host "WROTE AN ENTRY TO THE LOGFILE.`n" -foreground 'DARKGREEN' -background 'WHITE'
    Now, I'd like to also include this query... also changed information to protect the innocent.
    SELECT u.IDN_USER,      
    u.NAM_LASDBUSER,      
    u.NAM_FIRSDBUSER,      
    r.NAM_ROLE,      
    COUNT(o.IDN_ORDER) ORDER_CNT,      
    COUNT(DISTINCT
    o.IDN_CLIENT) CLIENDBCNT,
    (SELECT IDN_ZONE FROM DBUSER_PREF p WHERE u.IDN_USER = p.IDN_USER) IDN_USER_ZONE 
    FROM DBORDER o WITH (NOLOCK)       
    INNER JOIN DBUSER u WITH (NOLOCK)        
    ON o.IDN_USER_CRTD = u.IDN_USER       
    INNER JOIN DBROLE r WITH (NOLOCK)        
    ON u.IDN_ROLE = r.IDN_ROLE      
    WHERE DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)>=0 AND DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)<=0  
    AND r.IS_INTERNAL_USER = 1
    GROUP BY u.IDN_USER, u.NAM_LASDBUSER, u.NAM_FIRSDBUSER, r.NAM_ROLE, r.IS_INTERNAL_USER 
    ORDER BY u.NAM_LASDBUSER, u.NAM_FIRSDBUSER 
    Thank you in advance for any suggestions, links, etc, you can provide.  I don't mind doing the heavy lifting, ie:  research and reading, just needed to be pointed in the right directions.
    John

    As an example this is more readable but could be improved which would make your adding a section much easier.
    $DATETIME = Get-Date -Format 'MM-dd-yyyy [HH:mm:ss]'
    $LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME;
    Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING;
    $sql = @'
    SELECT count(DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT
    FROM FM_FAXIN fax WITH (NOLOCK)
    LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX
    WHERE
    fax.RESULT LIKE '%SUCCESS%' OR (
    fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0
    AND ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0
    AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK)
    WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION = 3) AND fax.DATE > '2013-09-25'
    $template=@'
    There are currently {0} Faxes in the Florida Inbound Fax Queue ( )
    Please Log in and help clear the Queue. Thank you.
    The people who recieved this email are: $EmailTo
    From ApexAdmin/SystemScheduler
    $subject= 'There are {0} faxes in the Inbound Florida Fax Queue. {1:MM-dd-yyyy [HH:mm:ss]}'
    $EmailFrom='[email protected]'
    $EmailTo = "My Email List"
    $SqlServer = "MY-SQL-SERVER"
    $SqlCatalog = "FAXmakerArchive"
    #run query
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
    $SqlConnection.Open()
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $sql
    $SqlCmd.Connection = $SqlConnection
    $NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
    $SqlConnection.Close()
    # build email if needed
    if($NumberOfFlaInboundFaxes -gt 29){
    $EmailBody=$template -f $NumberOfFlaInboundFaxes
    $EmailSubject = $subject -f $NumberOfFlaInboundFaxes,[DateTime]::Now
    $SMTPServer='smtp.gmail.com"'
    $SMTPClient=New-Object Net.Mail.SmtpClient($SmtpServer, 587)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password");
    $SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
    }else{
    Write-Host "NO ALERT on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
    Write-Host "There are currently $NumberOfFlaInboundFaxes Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
    Write-Host "SMTP Alert sent to $EmailTo on $DATETIME" -foreground 'DARKBLUE' -background 'WHITE' ;
    write-Host 'WROTE AN ENTRY TO THE LOGFILE.' -foreground 'DARKGREEN' -background 'WHITE'
    \_(ツ)_/

  • Pass jstl sql query result to jsp

    Hi I have the following code which works perfectly
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
    </sql:query>
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>   Now what I want is to perform the query in one page and then display the data in another, as such
    index.jsp
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
    </sql:query>
    <!-- NOT SURE WHAT TO DO HERE
    <jsp:useBean id="resultBean" scope="request"
         class="javax.servlet.jsp.jstl.sql.ResultSupport" />
    <jsp:setProperty name="rs" property="rs" />
    <jsp:forward page="test.jsp" />
    -->
        test.jsp
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:set var="items" value="${resultBean}" />
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>   I know in index.jsp I can use jsp forward and usebean but am not sure how to? What type is the result from the query? thanks

    Take a look at the "scope" attribute of the <sql:query> tag.
    query.jsp:
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <sql:setDataSource dataSource="jdbc/dbtest"/>
    <sql:query var="items" scope="request" sql="SELECT * FROM homepagesubscriptions"/>
    <jsp:forward page="test.jsp" />and then test.jsp:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
    <table border="0" align="center" valign="top">
    <c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
                   <tr>
                   <td>
                        <img src="${row.imgurl}" width="100" height = "100"></a>
                   </td>
                   <tr>
    </c:forEach>
    </table>  

  • PL/SQL function returning a SQL Query

    Is this only availabe in HTML db or in 10g in general? Where do I find more about this feature?
    Thanks in advance,
    Denes

    Not sure what you mean. HTML DB allows to use a PL/SQL function returning a valid SQL query in report regions.
    Its just a PL/SQL function returning a string, outside of HTML DB, I guess you can use it wherever it makes sense.

Maybe you are looking for

  • Unable to set IP address for VM creation using createVmBasedOnTemplate

    Hi, I'm trying to create VM using LifeCycleService - createVmBasedOnTemplate api The VM gets created and i m able to power on The ethernet cards are inactive when i checked thorugh console and IP address is not set So i'm unable to login to the VM us

  • How can I get to the desktop?

    Can't get to the desktop. When I press the Start button, or the combo Command-Ctrl-Start I get the musical cord but no desktop. I always shut it down with the Shut Down command from the Apple menu. Could this be another motherboard problem? The mothe

  • Modifying Portal URL to use Fully Qualified Domain Name

    Hi, We have a portal that I can access now by using the URL 'invsrvr001:50000/irj/portal'. We would need the URL to use the fully qualified domain name such as 'invsrvr001.company.com:50000/irj/portal'. Towards that end we added the profile paramter

  • "Safari quit unexpectedly" Error message. I cannot reopen Safari at all

    I can no longer open Safari.  Get error message "Safari quit unexpectedly" I cannot reopen Safari.  Read article on removing malware and removed tuneupmymac, still can't open

  • How avoid unnecessary upgrade? [SOLVED]

    Hi people! I'v just installed Arch base system from http://arm.kh.nu/core::2009-6-23/os/x86_64/ repository. I also changed core secton in pacman.conf to: [core] Server = http://arm.kh.nu/core::2009-6-23/os/x86_64/ But pacman -Suy complaining about al