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>

Similar Messages

  • Storing the SQL Query results as XML

    Hi All,
    I have a proc to select all the data from emp table and insert into another table. For some reason it inserts only one column and one record.
    I don't have any row limit or skip ...
    CREATE OR REPLACE procedure Convert_Data_Into_XML1
    as
    -- Var Declartion
    qryCtx DBMS_XMLGEN.ctxHandle;
    result CLOB;
    BEGIN
    qryCtx := dbms_xmlgen.newContext('SELECT * from emp');
    -- set the row header to be EMPLOYEE
    DBMS_XMLGEN.setRowTag(qryCtx, 'Employee-ROW');
    DBMS_XMLGEN.setRowsetTag(qryCtx, 'Employee-rowset');
    LOOP
    -- now get the result
    result := DBMS_XMLGEN.getXML(qryCtx);
    DBMS_OUTPUT.PUT_LINE ('In the Loop');
    EXIT WHEN DBMS_XMLGEN.getNumRowsProcessed(qryCtx) = 0;
    INSERT INTO temp_clob_tab VALUES (result);
    END LOOP;
    COMMIT;
    --close context
    DBMS_XMLGEN.closeContext(qryCtx);
    exception
    when others then
    dbms_output.put_line(TO_CHAR(sqlerrm));
    END;
    Basically I got this sample proc from Oracle website. As per the website I should be able to store all the records from emp table.
    How can I debug this.
    Here is the output from SQLPLUS&gt;
    SQL&gt; select result from temp_clob_tab;
    RESULT
    &lt;?xml version="1.0"?&gt;
    &lt;Employee-rowset&gt;
    &lt;Employee-ROW&gt;
    &lt;EMPNO&gt;7369&lt;/EMPNO&gt;
    &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;
    Thanks in advance
    Siva

    I am able to convert the SQL query output and I am able to store it in a XMLTYPE column.
    But the code doesn't work when I took the same code and try to Implement inside a Trigger. The reason I am doing this is, when there is an update or delete, I want to store the whole record as a XMLTYPE doc (before and After). But the code compiles fine, but when I tried to update a record it gives error.
    CREATE OR REPLACE TRIGGER INS_UPDDEV_EMP3_F
    BEFORE UPDATE OR DELETE ON EMP
    FOR EACH ROW
    DECLARE
    V_DBUSER VARCHAR2(50);
    V_CHANGETYPE VARCHAR2(20) := 'INSERT' ;
    QRYCTX DBMS_XMLGEN.CTXHANDLE ;
    OLDVALUE XMLTYPE;
    NEWVALUE XMLTYPE;
    BEGIN
    IF :OLD.EMPNO &lt;&gt; :NEW.EMPNO or DELETING then
    ---------- old Value
    QRYCTX := DBMS_XMLGEN.NEWCONTEXT ('SELECT :OLD.EMPNO, :OLD.ENAME, :OLD.JOB, :OLD.MGR, :OLD.HIREDATE, :OLD.SAL, :OLD.COMM, :OLD.DEPTNO FROM EMP WHERE EMPNO=:OLD.EMPNO ');
    DBMS_XMLGEN.SETROWTAG (QRYCTX, 'DEPTROW');
    DBMS_XMLGEN.SETROWSETTAG(QRYCTX, 'DEPTSET');
    OLDVALUE := XMLTYPE(DBMS_XMLGEN.GETXML(QRYCTX));
    ------------------------- new Value
    QRYCTX := DBMS_XMLGEN.NEWCONTEXT ('Select * WHERE EMPNO=:NEW.EMPNO '); -- WHERE :OLD.EMPNO
         DBMS_XMLGEN.SETROWTAG (QRYCTX, 'DEPTROW');
    DBMS_XMLGEN.SETROWSETTAG(QRYCTX, 'DEPTSET');
    NEWVALUE := XMLTYPE(DBMS_XMLGEN.GETXML(QRYCTX));
    V_CHANGETYPE := 'UPDATE' ;
    INSERT INTO ADM_RECAUDITHISTORY VALUES ('table emp', 'fIELD all', OLDVALUE, OLDVALUE,
    V_CHANGETYPE , SYSDATE, 'TIGER TRIG');
    commit;
    END IF;
    END;
    I am getting the following error while updating the record.
    &gt;&gt;&gt;&gt;
    ERROR at line 1:
    ORA-19206: Invalid value for query or REF CURSOR parameter
    ORA-06512: at "SYS.DBMS_XMLGEN", line 83
    ORA-06512: at "SCOTT.INS_UPDDEV_EMP3_F", line 13
    ORA-04088: error during execution of trigger 'SCOTT.INS_UPDDEV_EMP3_F'
    &gt;&gt;&gt;&gt;&gt;
    Is anyone knows why I am getting this error.
    Thanks
    Siva

  • How to write sql query to parse xml?

    Hi, I am new to this parsing xml. I need to extract value from xml using sql query. Please find the sample xml file. Kindly help me.
    <?xml version="1.0" encoding="UTF-8"?>
    <MaterialUpdates>
      <Materials>
         <SalesOrg>
           <ID>KAR12</ID>
         </SalesOrg>
    </Materials>
    </MaterialUpdates>
    I need to extratct ID value : /MaterialUpdates/Materials/SalesOrg/ID

    Thanks once again, it is working as per your suggestion. One last question .. how about in case of there is multiple nodes.
    Please find sample xml below:
    <?xml version="1.0" encoding="UTF-8"?>
    <MaterialUpdates>
      <Materials>
         <SalesOrg>
           <ID>KAR12</ID>
         </SalesOrg>
         <SalesOrg>
           <ID>KAR13</ID>
         </SalesOrg>
         <SalesOrg>
           <ID>KAR14</ID>
         </SalesOrg>
    </Materials>
    </MaterialUpdates>
    The above mentioned sql query works fine when there is one occurance of SalesOrg - ID, but fails when there is multiple occurance.

  • 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 convert the sql query result into xml ? PLease..Please..

    I have a table Submission Record which contain a field with mix with text string and xml data type.
    Table name: Submission Record
    Field name: RCA
    Jason
    Tomato
    <Record>AA</Record>
    Fish
    Brother
    <Record>BB</Record>
    <Record>CC</Record>
    Tom is a girl
    Its mixing with text and xml data.
    I wish to convert all into xml data as per request from management.
    my select statement is like below...but i think it may contain syntax error. Wish to get help from here.
    sqltestagain = "select '<DATA>' || RCA || '</DATA>' from Submission Record".
    Expect below will display
    <DATA>Jason</DATA>
    <DATA>Tomato</DATA>
    <DATA><Record>AA</Record></DATA>
    or any other solution for it ??
    I've tried FOR XML....DBMS_XML......but none of it worked.....

    also look at xmlelement
    SQL> select xmlelement("DATA", rca).getstringval() from
      2  (
      3  select 'Jason' RCA from dual union all
      4  select 'Tomato' from dual union all
      5  select '<Record>AA</Record>' from dual
      6  )
      7  /
    XMLELEMENT("DATA",RCA).GETSTRI
    <DATA>Jason</DATA>
    <DATA>Tomato</DATA>
    <DATA>&lt;Record&gt;AA&lt;/Record&gt;</DATA>
    SQL>

  • 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

  • How to Parse JSP query results to XML Document ???

    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 ? )
    My question is how do I go about doing this ? Any sort of suggestion , help, reference would be deeply appreciated ..Thanks !

    Why not take the result set and populate zero or more Java objects with data from each row in the result set? Then you can easily sort the data by putting the objects into a collection and using different Comparator objects for your sort. I'm just not sure why you want to use XML if the data isn't getting transfered between systems. In my experience XML is best used when you need a readable content for something (such as a properties file) or you want to share data between systems. I might be missing something, but I think you are better off storing your data in java and sorting it there.

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

  • 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

  • Output query result in XML format

    folks:
    could anybody provide more information
    about how to generate query result in
    xml format? looks like DBXML is for demo only
    and i have heard that PLSQL XML parser is the way to go; so far i have not found
    a sample yet on how to actually
    do the XML generation; if you know more
    about it, please let me know; thanks in
    advance.
    Bill

    Here are some sample apps that might interest you:
    [list]
    [*][url [URL=http://technet.oracle.com/tech/xml/xsql_servlet/index2.htm?Code&files/ffhome.html]The]http://technet.oracle.com/tech/xml/xsql_servlet/index2.htm?Code&files/ffhome.html]The XML Flight Finder
    [*][url [URL=http://technet.oracle.com/sample_code/tech/xml/xmlb2b/doc/xb2bhome.html]B2B]http://technet.oracle.com/sample_code/tech/xml/xmlb2b/doc/xb2bhome.html]B2B with XML
    [list]
    Enjoy,
    -rh

  • 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

Maybe you are looking for