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

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

  • Export query result to csv using Export Wizard

    Been a decade since I last used Oracle and related tools.
    I had to use Oracle server again, I have a query over multiple tables, I am to run a scheduled script that will spit out the query result as a csv file.
    I started with SQL Developer Export wizard, in step "Specify Data", I am at a loss, where to specify the query itself? I see a Name,Schema,Type input, a text area below, Up,UpAll,Down,DownAll buttons etc etc. Where do I specify my query here? Can someone please help?
    Is this the best way to go about to schedule a data export (query to csv) daily?

    To export a user query rather than a whole table, run it in a worksheet and export using the context menu on the result grid. However none can be scheduled.
    Instead you can look at the SPOOL command and schedule it through SQL*Plus. Any questions can go to the iSQL*Plus and/or SQL And PL/SQL forum.
    Have fun,
    K.

  • Export query results into .csv file?

    Hello I have a T-SQL script that gets row counts for a specified date range and then needs to loop (by incrementing +1 day to get the next day's counts) for a large date range.  I'm aiming to output & append each query results day counts
    into a .csv file via a SQL Agent job since this will take quite a while to complete.
    Would using the following as an example template...
    INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
    SELECT Field1, Field2, Field3
    FROM DatabaseName
    ...be the method or something else?
    If this is good to use I've tried running this but get the following error:
    Msg 7357, Level 16, State 2, Line 76
    Cannot process the object "SELECT * FROM [FileName.csv]". The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions
    on that object.
    Thanks in advance.

    Hi Techresearch7777777,
    The error in your post says that the file FileName.csv has to be created with the column names in the first row. Like:
    Field1,Field2,Field3
    Either you can create a schema.ini file under the same folder:
     [FileName.csv]
     Format=CSVDelimited
     ColNameHeader=False
     Col1=Field1 [DataType]
     Col2=Field2 [DataType]
     Col3=Field3 [DataType]
    For the [DataType],you can reference
    Schema.ini File (Text File Driver)
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Extract SQL Query Results to 'xlsx' bogs down at 150,000 rows

    Environment:
    SQL*Developer 3.1.07.42 on Windows XP SP3
    Oracle 11.2.0.3 EE on Solaris 10.5
    I ran a query in a worksheet window and the first page of results came back in 10 seconds, whoo hooo!
    I right-clicked the first column in the first row and selected 'Count Rows' and it returned 527,563 after thinking a bit.
    I right-clicked 'Export', selected a format of 'xlsx', unchecked the box for 'Query Worksheet Name' and browsed to specify the output file directory (my local C: drive) and file name. I clicked 'Next' and then 'Finish'.
    I watch the row counter at the bottom right of the window and it went very fast until it hit about 150,000 rows and then it started slowing down. It got slower and slower and slower and slower, well you get the picture, and I finally killed the process when it took over 15 seconds to get from 156,245 to 156,250.
    Why would this be?
    Additional information:
    I ran the exact same query again and exported the same 527,563 rows using the 'xls' format instead of 'xlsx' and the process proceeded very quickly all the way to the end and completed successfully in just several minutes. The resultant spreadsheet contained eight (8) worksheets since it could only put 65536 rows into each worksheet. This was acceptable to the user who simply merged the data manually.
    Is there some issues with using 'xlsx' as the output format as opposed to just using it as an input format?
    Does SQL*Developer try to create a spreadsheet with as many rows as the data up to the max in Excel 2010 (which is more than 527,563)?
    Thanks very much for any light shed on this issue. If I've left out any important details please let me know and I'll try to include them.
    -gary

    Hi gary,
    You may have already seen one or more threads like the following on the issue of increased memory overhead for the Excel formats:
    Re: Sql Developer 3.1 - Exporting a result set in xls generates and empty file
    Basically SQL Developer uses a third-party API to read and write these Excel formats. There are distinct readers and formatters for each of the xls and xlsx forms.
    There is a newer version of the API that supports streaming of xlsx Workbooks. Basically it achieves a much lower footprint by keeping in memory only rows that are within a sliding window, while the older, non-streaming version gives access to all rows in the document. The programmer may define the size of this window. I believe the newer API version was either not available or not stable during our 3.1 development cycle. Possibly a future SQL Developer version might use it.
    Regards,
    Gary
    SQL Developer Team

  • How to upload the web query result  to CSV/Text file

    Hi,
    Kindly help me on the following.
    1)       I have info-provider (IP), which has info-objects "company code" and "supplier".
    2)       I built a query by putting company-code with a variable in free-charateristics and supplier-code in row.
    3)       When I run this query, it will ask company-code as input and the result will be filtered using company-code.
    4)       For this query, I created a web-template and assigned data-provider to display the data on the web.
    5)       The user wants to enter input company-code='1000' and write the data in a CSV file in a specific directory. i.e, by clicking the execute button (after entering company code) , the result should go to the CSV or text file. i.e. the application should automatically generate the file with query results.
    Note: The user should not use context menu to EXPORT TO CSV OR EXCEL file.
    Please let me know, if there is any tutorial. Thanks a lot advance help.
    Regards
    Kandasamy

    1. SELECT INTO
    Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
    Use AdventureWorks2008R2;
    Go
    ---Insert data using SELECT INTO
    SELECT AddressLine1, City
    INTO BothellAddresses
    FROM Person.Address
    where City = 'Bothell';
    GO
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    2. INSERT INTO SELECT
    Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
    another table.
    Use AdventureWorks2008R2;
    Go
    ---Create Table
    CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
    ---Insert into above table using SELECT
    INSERT INTO BothellAddresses(AddressLine1, City)
    SELECT AddressLine1, City
    FROM Person.Address
    where City = 'Bothell';
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    Regards,
    Vishal Patel
    Blog: http://vspatel.co.uk
    Site: http://lehrity.com

  • Export a query results to CSV

    Hi all,
    I am currently planning to develop a program that does the following things:
    1. Connects to the Oracle database
    2. Runs a query
    3. Export the results of the query to a CSV file in a folder
    If theres anyone out there who has experienced in similliar work, please explain to me with codes as example or point to me tutorials.
    cheers
    SI

    jwenting wrote:
    johndjr wrote:
    jschell wrote:
    johndjr wrote:
    DrClap wrote:
    Of course there are people who can't tell the difference between a CSV file and an Excel spreadsheet.And a good thing I say. I deal with a number of people who love their spreadsheets. I can create a simple CSV file and when they double click on it on Windows, Excel opens a spreadsheet and we are both happy.I bet they would be happier if it was a real spreadsheet.You would almost certainly win that bet.I doubt many of them would even notice :)++

  • 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

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

  • Sql query question - been trying for two days

    Hi guys im trying to carry out an sql query
    Im using a left join to do a query, which gives me a set of results:
    select COURSESTUDENT.StudentNo, COURSESTUDENT.CourseCode, COURSESTUDENT.Year, MARKS.ExamMark, MARKS.EntryNo FROM COURSESTUDENT LEFT JOIN MARKS ON COURSESTUDENT.StudentNo=MARKS.StudentNo AND COURSESTUDENT.CourseCode=MARKS.CourseCode AND COURSESTUDENT.Year=MARKS.Year
    but I would like to do a select on this result but do not want to use a create view as if more than one person access this page at a time then if the servlet tries to create the view an error will occur.
    I would like to do the following select statement on the results of the query above..
    select * from (above) where CourseCode='ELE304' AND Year=1999;
    Is this possible, im using postgres..
    Please help......
    thanks
    tzaf

    Sorry, I have never used postgres, but in several databases, the following syntax would work and provide the correct ResultSet.
    select *
    from (
         SELECT
             COURSESTUDENT.StudentNo,
             COURSESTUDENT.CourseCode,
             COURSESTUDENT.Year,
             MARKS.ExamMark,
             MARKS.EntryNo
         FROM
             COURSESTUDENT LEFT JOIN MARKS ON
             COURSESTUDENT.StudentNo=MARKS.StudentNo AND
             COURSESTUDENT.CourseCode=MARKS.CourseCode AND 
             COURSESTUDENT.Year=MARKS.Year
         ) A
    WHERE
        CourseCode='ELE304' AND
        Year=1999

  • Exporting BEx Query results to CSV or other files.

    Hi All,
    We have a report designed in WAD, which uses a BEx query to display department’s information. Because of amount of data in the results it crashes when u get all the Free Characters into ROWS(Error is : Result set too large(552244 cells); data retrieval restricted by configuration (maximum =500000 cells).  It is a requirement from the user to have all the free characteristics in the rows( which I can understand is not the right way to go ahead). As it is crashing when you add last characteristic(WBS Purpose)  into the rows, they aren’t able to export data into spread sheet from the results. (as there are no results)
    Now my question is…..is there any way we can export the results from BEX query into any format for example text or csv? If yes, can we schedule that process? Please note that this characteristics are displayed as hierarchies.
    Am new to SAP BW and its been only six months since I have been in this role. Any help would be much appreciated???
    I looked online and some where in the forum it was mentioned of using program RSCRM_BAPI, but looks like it needs some sort of downloads from SAP.
    Is there any other way to export the BEx query results?
    Cheers
    Sandeep

    Hello Sandeep,
    You can use the Item "Context Menu" in your WAD and in the properties by default you can see the Options:
    Export to Excel & Export to CSV will be there and also there are many options which you wanted to see.
    It works for you!!!
    With Regards,
    PJ.

  • How to get the sql query result?

    Hi,
    Currently I am using LV2012 to connect a Oracle database server. After the installations/settings for Oracle Express and Oracle ODBC driver done.
    I am sucessfully to use the SQL command to query the data through my window command prompt. 
    Now the problem is, how I do the same task in Labview by using the database connectivity toolkits?
    I have build a VI for query as attached, but i have no idea what pallete to use to get the query result.
    Please help me ~~
    Solved!
    Go to Solution.
    Attachments:
    Query.vi ‏9 KB

    Here is a piece of code I use to test SQL commands, you can use the part that retrieves sql results.
    It is also possible to get the column headers back, but that is for next lesson!
    Attachments:
    RunSQLCommand.vi ‏30 KB

Maybe you are looking for

  • Lightroom Gallery in Dreamweaver.

    I was making a flash web gallery in Lightroom, and was wondering what I need to do in order for Flash Player to display my images, because right now it's just blank. Thanks. I'm currently using Dreamweaver 8 but I also have cs3 on another computer. A

  • Install Crash of ODT 10.2.0.2.20 - Can't Find gacutil.exe

    Win XP SP2<br> VS 2005 Pro<br> <br> Trying to install ODT 10.2.0.2.20 and the instal gets to about 96% complete when it throws an error when trying to do the following operation: <p>"spawning 'C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\\bin\

  • My SAP SRM Application Monitors Purchase order / local errors

    I am seeing local errors in the monitor under Purchase order. The message is incorrect status in pricing, but when i click on the message i get no further information. How can I track there errors

  • Call Library Function - Function not found in library

    Hello, I am working with a .dll in LabView 5.1. I finished a little program that should give me the number of CPCI-cards in a PXI-machine. But now i always get the error messages "Call Library Function - Function not found in library". I know it is t

  • Photoshop CS3 not installing on macbook

    My photoshop's installer is not mounting. I can hear the disc running in the macbook, but nothing happens. I'm using lion, and its my first time so i don't know if its the same as on snow leapord. i'm pretty sure the disc is clean and i'm planning on