How to order SQL query results in order given in IN Clause

Hi,
I Need to construct a query, which takes a string as input and results for those should be sorted in the order in which request was made.
Say, we have a couple of students, and the grades in different subjects to be the result of the query.
If John and Jane are the two students,
and if input is John,Jane
my output should be listing John, his subjects and grades
and then Jane, her subjects and grades.
I read somewhere in other posts, that i could use a query combined with regular expression to split a string into a temp table/array and use this as my input for my select query. Then use the rownum or level from this temp table to sort the data in order sent in.
But am not able to put together a query which would work for me.
Anyone with any pointers on this would be highly appreciated.
Thanks

Hi,
[This thread|http://forums.oracle.com/forums/thread.jspa?threadID=702891&tstart=0] is about splitting up delimited lists. You'll want to keep the n-th value from the user-supplied list, as well as n itself, in a result set, so you can use it in both your WHERE- and your ORDER BY clause.
If you're using SQL*Plus, you can also keep the whole list in a substriution variable, and use INSTR to see where individual values appeard in that list. Personally, I'd trust the first method (split and store) more.

Similar Messages

  • 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 use SQL query result in DOS commands

    Hi
    Currently i am runnig below DOS commands manually
    d:\apps\bin>TrueGridsCalc period="Aug 2010"
    Now I want to write one batch file and schedule job on windows and make value of "period" to be dynamic. So to get that value i need to fetch it from DB
    Steps which i am taking are
    1. connect DB from command line (using SQLPLUS)
    2. run query to fetch result
    3.How to use query result in "period" parameter ?
    I am good at step 1 and 2. Dnt know how to use query result in command to make it dynamic
    Thank you
    Sachin
    Edited by: sachin.mali on Oct 26, 2010 4:39 PM
    Edited by: sachin.mali on Oct 26, 2010 4:43 PM

    sachin.mali wrote:
    Hi
    Currently i am runnig below DOS commands manually
    d:\apps\bin>TrueGridsCalc period="Aug 2010"
    Now I want to write one batch file and schedule job on windows and make value of "period" to be dynamic. So to get that value i need to fetch it from DB
    Steps which i am taking are
    1. connect DB from command line (using SQLPLUS)
    2. run query to fetch result
    3.How to use query result in "period" parameter ?
    I am good at step 1 and 2. Dnt know how to use query result in command to make it dynamic
    Thank you
    Sachin
    Edited by: sachin.mali on Oct 26, 2010 4:39 PM
    Edited by: sachin.mali on Oct 26, 2010 4:43 PMYOu'll have to have sqlplus spool the output to a file, then figure out some way of parsing that file. Too bad you're stuck with Windows. With any *nix you could do the file parsing with one line of code.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to print sql query results

    how to print sqlplus query results

    Hi,
    Spool sql.txt
    Execute the query
    Spool off
    And find the sql.txt file in the current directory.
    Regards
    Jafar

  • 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.

  • How to obtain sql query result in JavaScript

    hello, i want to know if this is possible : i have a Javascript function that make this:
    var szPLANT = document.getElementById("hid_Plant").value;
       var szLINE = document.brs_Line.getSelectedItem();
       var cell = document.brs_Cell.getSelectedItem();
       var GetLineDownload = document.GetLineDownload.getQueryObject();
       document.GetLineDownload.getQueryObject().setParam(1,szLINE);
       document.GetLineDownload.getQueryObject().setParam(2,cell);
       document.GetLineDownload.executeCommand();
    but i to catch the result of the sql ...to use in another things in this function...how to to this?..like this:
    result = document.GetLineDownload.results
    regards
    Mário

    Mario,
    your script suggests that you are using a iCommand query. The iCommand is used to execute a query that does not return a value, like an update, insert or delete query.
    If you are expecting a result, you would normally use an iGrid, and then you can use the functions that Suresh proposed to read out the result cells. If you do not want the iGrid to be displayed, but only need the values in your JavaScript, then you can omit the "DisplayTemplate" parameter in your iGrid so it won't be displayed on the web page.
    You can however read the values from the iCommand also by using the function "iCommand.getValue(Col, Row)".
    Please have a look at [http://help.sap.com/saphelp_xmii120/helpdata/en/44/d91ad2d06f3ee2e10000000a114a6b/content.htm].
    Michael
    Edited by: Michael Otto on Nov 13, 2009 1:25 PM

  • Query Result Column Order

    I'm working with an embedded db query that specifies columns
    by name in the result set, i.e., no *. However, the order of the
    columns in the result set seem to be quite random - or at least
    dependent on which column is being searched. I'm showing the
    results via "resultsGrid." How do I enforce a consistent column
    order in query results?
    Thanks,
    Al

    What you describe boils down to a reinvention of materialized views.
    Did you consider using them?
    Sybrand Bakker
    Senior Oracle DBA

  • How to get the query result of improvement (Before and After ) using sql de

    how to get the query result of improvement (Before and After ) using sql developer.

    Check
    http://www.oracle.com/technetwork/articles/sql/exploring-sql-developer-1637307.html

  • How to output a query results into a text file

    How to output a query results into a text file instead of outputing it to the screen..
    is there a way for us to write a SQL query which specifies to output the query results to a text file.
    Pls let me know how to do it
    Thanking u in advance
    regards
    Muraly

    Muraly,
    If you are using SQL*Plus 8.1.6 or later, you can also spool output to a file in HTML format, eg
    SET MARKUP HTML ON SPOOL ON PREFORMAT OFF ENTMAP ON
    SPOOL c:\temp\report.html
    SELECT DEPARTMENT_NAME, CITY
    FROM EMP_DETAILS_VIEW
    WHERE SALARY>12000;
    SPOOL OFF
    SET MARKUP HTML ENTMAP OFF
    In iSQL*Plus 9.0.1 (the browser-based interface to SQL*Plus) onwards, you can also send the HTML output to a new web browser window, or an html file -- much easier than the command line method.
    Alison

  • How to execute SQL Query in Code behind Using infopath 2010?

    Hi,
    I've repeatable on infopath form, and want bind it throuth code behind from SQL table. My question is that how to execute SQL Query in code behind from infopath as well as how would get Query result to bind repeatable control?
    Thanks In Advance
    Shoeb Ahmad

    Hello,
    You first need to add new SQL DB connection then you need execute connection from code behind.
    See below link to create new connection
    http://office.microsoft.com/en-in/infopath-help/add-a-data-connection-to-a-microsoft-sql-server-database-HP010092823.aspx:
    http://www.bizsupportonline.net/infopath2010/connect-infopath-2010-sql-server-2008-table.htm
    Then use below code to execute this connection:
    AdoQueryConnection conn = (AdoQueryConnection)(this.DataConnections["Data connection name"]);
    string origCommand = Select * from tablename;
    conn.Command = origCommand;
    conn.Execute();
    Finally bind your table:
    http://www.bizsupportonline.net/infopath2007/4-way-programmatically-add-row-repeating-table.htm
    http://stevemannspath.blogspot.in/2010/09/infopath-20072010-populate-repeating.html
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • 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

  • How to write sql query for below mentioned eaxmple.

    Hi,
    I have requirement.
    There are number of rows and I need the result through query as follows.Please help me to proved sql query for below mentioned requirement.
    example: table TEST.
    COLA COLB COLC COLD COLE COLF MANAGER 5 NULL NULL 3 NULL
    SR.MANAGER 6 3 NULL NULL NULL
    VP 5 5 4 5 5
    I have to write the sql query if COLA IS MANAGER THEN CONSIDER MANGER RECORD,AND IF ANY COLUMN FILED IS NULL FOR MANGER THEN CONSIDER COLA IS SR.MANGER, AND IF ANY COLUMN FILED IS NULL FOR SR,MANGER THEN CONSIDER VP records.
    I need output as below.
    COLB COLC COLD COLE COLF
    5(manager) 3(sr.manger) 4(vp) 3(manger) 3(vp)
    Please provide the for above mentioned output.
    Thanks

    Duplicate thread. please view the answer posted in your first thread.
    how to write sql query.
    And, please don't post any duplicate thread.
    Regards.
    Satyaki De.

  • How to use sql query in java ?

    i don't know how to use sql query in java code.
    who can give me some advice?
    thanks

    http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/

  • How to Use SQL Query having IN Clause With DB Adapter

    Hi,
    I am using 11.1.1.5 want to find out how to Use SQL Query having IN Clause With DB Adapter. I want to pass the IN values dynamically. Any ideas.
    Thanks

    invoke a stored procedure, it's safer than trying to put together an arbitrary SQL statement in the JCA adapter

  • How to write sql query with many parameter in ireport

    hai,
    i'm a new user in ireport.how to write sql query with many parameters in ireport's report query?i already know to create a parameter like(select * from payment where entity=$P{entity}.
    but i don't know to create query if more than 1 parameter.i also have parameter such as
    $P{entity},$P{id},$P{ic}.please help me for this.
    thanks

    You are in the wrong place. The ireport support forum may be found here
    http://www.jasperforge.org/index.php?option=com_joomlaboard&Itemid=215&func=showcat&catid=9

Maybe you are looking for