SQL SELECT result
try {
// Create a result set containing all data from my_table
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM station WHERE stationID = '" + stationID + "'");
} catch (SQLException e) {
}If there are no rows for that SQL statement, what will it return back to me? On my server, a client is sending a packet to me that contains the stationID. First, I want to make sure stationID already exists in the database. If it doesn't exist, I would like to run more SQL statements, but first I need to know what it will return to me.
In guessing code, this is what I'm looking for: try {
// Create a result set containing all data from my_table
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM station WHERE stationID = '" + stationID + "'");
if (rs == NULL) // if no rows were selected
// if there were no rows selected from the original SELECT statement, INSERT a new row using this query
ResultSet rs = s.executeQuery("INSERT INTO station VALUES ('stationID', 'address', 'city', 'state', zip'");
} catch (SQLException e) {
}Any help?
Message was edited by:
tristanlee85
Why would you guess when you can just look at the API documentation? (Which specifically says the executeQuery() method never returns null.)
If the SQL statement returns zero rows, you get a ResultSet that contains zero rows. Does that seem peculiar to you? In that case calling "rs.next()" returns false because there are zero rows.
Similar Messages
-
Sql (Select) result in string
Hi , I found this code in internet but it´s put a result in range on excel.
I would like some code with end is some like "MyVarString = objMySQLRecordsetResult"
For example: In my select result = "User01" , I would like put this value in a var string.
The code ends ...
'ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset
I want ...
Test01 = Recordset objMyRecordset
tks for your help !!
Public Sub GetDataFromADO()
'Declare variables'
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Dim TESTE01 As String
'Open Connection'
objMyConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source="
& ActiveWorkbook.Path & "\Database.accdb" & "; Jet OLEDB:Database Password= `MY PASSWORD"
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "select DUSER from DUSER WHERE DUSER = 'USUR01 "
objMyCmd.CommandType = adCmdText
'Open Recordset'
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
objMyRecordset.OpenRecordset
'Copy Data to Excel'
'ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset
End SubTry:
Public Sub GetDataFromADO()
Dim Conn As New ADODB.Connection
Dim Rs As New ADODB.Recordset
'Open Connection'
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & ActiveWorkbook.Path & "\Database.accdb" & "; Jet OLEDB:Database Password= `MY PASSWORD"
Conn.Open
'Open Recordset'
Rs.Open "select DUSER from DUSER WHERE DUSER = 'USUR01'", Conn, adOpenDynamic, adLockReadOnly
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset Rs
Rs.Close
Conn.Close
End Sub
Rod Gill
Author of the one and only Project VBA Book
www.project-systems.co.nz -
Assign SQL select result to a java variable
In a custom IKM, I need to check the LOGGING setting of target table, save the setting, then change the setting, then restore the setting.
I am having problem saving the setting. I do something like the following, where tgtLogging is the current LOGGING setting of the target table. I need to save the value to sTgtLogging so that it can be accessed in a later step. I can't figure out the syntax. just saying sTgtLogging = tgtLogging does not work either in the pl/sql or the <% %> context.
<%
String sTgtLogging = "";
%>
declare
tgtLogging varchar(5);
begin
select logging into tgtLogging from dba_tables where table_name='<%=odiRef.getPop("TABLE_NAME")%>';
some other code.....
end;
Edited by: user611482 on Jul 8, 2010 3:34 PMHi,
we use this for saving the login time of the user. There are few therads about creating a custom login module (for example: [Custom Login Module - how to go on |http://forums.sdn.sap.com/thread.jspa?threadID=357616]).
We have created a login module which extends AbstractLoginModule, in login() method :
public boolean login() throws LoginException {
Object option = g_sharedState.get("javax.security.auth.login.name");
if (option != null && !option.equals("")) {
String l_userID = (String)option;
IUserAccount l_account = UMFactory.getUserAccountFactory().getUserAccountByLogonId(l_userID);
IUserAccount mutableAccount = accountFactory.getMutableUserAccount(account.getUniqueID());
l_mutAccount.setLastSuccessfulLogonDate(new Date());
l_mutAccount.commit();
about login modules and login stacks start here: [http://help.sap.com/saphelp_nw04/helpdata/en/8c/f03541c6afd92be10000000a1550b0/frameset.htm|http://help.sap.com/saphelp_nw04/helpdata/en/8c/f03541c6afd92be10000000a1550b0/frameset.htm]
Hope this helps,
Romano -
Colorize report results depending on sql selects
Hy,
is it possible to colorize report results depending on sql selects.
For example: select id, name from db where name = 'frankfurt' or name = 'munic'
All Results munic in red colour.
Thanks
TomHi,
I have tried using the following in a decode statement of a Region report (type is SQL Query), and all it seems to do is form the HTML text as expected, but does not actually do what I want (i.e. display the field as red):-
SELECT a_code, a_status, decode(a_fld,a_fld,'<font color="FF0000">'||a_fld||'</font>','other') "CA" from a_table
What appears in the report is literally (I've put in single quotes in case this line is interpretted in the forum):
'<font color="FF0000">1234</font>'
I'm missing something - to force the HTML to be rendered as such. The field is displayed as a Standard Report Column, but it's just taking the decode search field as an ordinary piece of text. There's something that needs setting, but I can't find it - does anyone know?
Thanks in advance
Dave -
Oracle SQL Select query takes long time than expected.
Hi,
I am facing a problem in SQL select query statement. There is a long time taken in select query from the Database.
The query is as follows.
select /*+rule */ f1.id,f1.fdn,p1.attr_name,p1.attr_value from fdnmappingtable f1,parametertable p1 where p1.id = f1.id and ((f1.object_type ='ne_sub_type.780' )) and ( (f1.id in(select id from fdnmappingtable where fdn like '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#%')))order by f1.id asc
This query is taking more than 4 seconds to get the results in a system where the DB is running for more than 1 month.
The same query is taking very few milliseconds (50-100ms) in a system where the DB is freshly installed and the data in the tables are same in both the systems.
Kindly advice what is going wrong??
Regards,
PurushothamSQL> @/alcatel/omc1/data/query.sql
2 ;
9 rows selected.
Execution Plan
Plan hash value: 3745571015
| Id | Operation | Name |
| 0 | SELECT STATEMENT | |
| 1 | SORT ORDER BY | |
| 2 | NESTED LOOPS | |
| 3 | NESTED LOOPS | |
| 4 | TABLE ACCESS FULL | PARAMETERTABLE |
|* 5 | TABLE ACCESS BY INDEX ROWID| FDNMAPPINGTABLE |
|* 6 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
|* 7 | TABLE ACCESS BY INDEX ROWID | FDNMAPPINGTABLE |
|* 8 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
Predicate Information (identified by operation id):
5 - filter("F1"."OBJECT_TYPE"='ne_sub_type.780')
6 - access("P1"."ID"="F1"."ID")
7 - filter("FDN" LIKE '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#
8 - access("F1"."ID"="ID")
Note
- rule based optimizer used (consider using cbo)
Statistics
0 recursive calls
0 db block gets
0 consistent gets
0 physical reads
0 redo size
0 bytes sent via SQL*Net to client
0 bytes received via SQL*Net from client
0 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
9 rows processed
SQL> -
How to capture all the rows returned from a sql select query in CPO
Hi,
I am executing an sql select query which returns multiple rows. I need to capture the values of each row to specific variables. How do I proceed.
Thanks,
SwatiThe select activities ("Select from Oracle," Select from SQL Server," etc.) against database already return tables. Use one of the database adapters to do your select, and it will already be in a table form. Just put your query in the select and identify the columns in your result table. The online help or the database adapter guides in the product documentation can help.
-
I have 2 tables
Table Parent_child_table:
ID | Parent_id | Name
1 | NULL | Kitchen
2 | 1 | Freezer
3 | NULL | Garden
4 | 3 | Grass
Table Products:
ID | parent_child_table_ID | Price | Comment
1 | 2 | 111 | aaaa
2 | 4 | 12 | vv
I want to select Name from parent table where selected child ID are in PRODUCT table.....
The result would like:
|NAME|
|Kitchen
|Garden
Can someone help with this SQL SELECT ?Raivis wrote:
I have 2 tables
Table Parent_child_table:
ID | Parent_id | Name
1 | NULL | Kitchen
2 | 1 | Freezer
3 | NULL | Garden
4 | 3 | Grass
Table Products:
ID | parent_child_table_ID | Price | Comment
1 | 2 | 111 | aaaa
2 | 4 | 12 | vv
I want to select Name from parent table where selected child ID are in PRODUCT table.....
The result would like:
|NAME|
|Kitchen
|Garden
Can someone help with this SQL SELECT ?A guess
select
p.name
from Parent_child_table p
where p.parent_id is null
and exists
select
null
from Parent_child_table p1, products p2
where p1.id = p2. parent_child_table_id
and p1.parent_id = p.id
)The reason it's a guess is because you've really done nothing to outline WHY you should get the results you say you would like. The more time you spend creating a clear question, the less time you'll have to spend weeding through useless answers.
Cheers, -
Lookup by SQL select in ODS tables and source package
Hi all
I load FI data in ODS and need some extra info from older ODS records.
In my Update rule for target InfoObject I created 2 SQL selects on Active Data and New data tables of ODS. Selects worked fine while testing them as separate program, but I got no data while data load.
I guess, the data I need was in the same data package during data load. So I assume, besides Active/New data selects, I need to check data on SOURCE_PACKAGE. Is it possible on update rule level of InfoObject? Could you please, provide me some ABAP example?
thanx in advance, points will be awarded.SELECT in field routine:
==========================================================
DATA src_doc_no(10) TYPE c.
DATA src_item_num(3) TYPE c.
DATA src_year(5) TYPE c.
DATA src_doc_typ(2) TYPE c.
if ( COMM_STRUCTURE-AC_DOC_TYP = 'DD' or COMM_STRUCTURE-AC_DOC_TYP =
'LD' ) and STRLEN( COMM_STRUCTURE-REF_KEY3 ) = 17.
CONCATENATE COMM_STRUCTURE-REF_KEY3+0(4) '%' INTO src_year.
src_item_num = COMM_STRUCTURE-REF_KEY3+15(3).
src_doc_no = COMM_STRUCTURE-REF_KEY3+4(10).
select from NEW data of ODS:
SELECT AC_DOC_TYP into src_doc_typ
FROM /BI0/AFIAR_O0340
WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
AND DEBITOR = COMM_STRUCTURE-DEBITOR
AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
AND AC_DOC_NO = src_doc_no
AND ITEM_NUM = src_item_num
AND FISCPER like src_year.
endselect.
if src_doc_typ = ''.
select from ACTIVE data of ODS:
SELECT AC_DOC_TYP into src_doc_typ
FROM /BI0/AFIAR_O0300
WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
AND DEBITOR = COMM_STRUCTURE-DEBITOR
AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
AND AC_DOC_NO = src_doc_no
AND ITEM_NUM = src_item_num
AND FISCPER like src_year.
endselect.
endif.
RESULT = src_doc_typ.
endif.
============================================ -
Oracle 9i bad SELECT result?
Hi people,
Here is a doozy for everyone....
Can someone please explain the following behaviour to me?
I was trying to setup some test data for a unit test ( I wanted to select a random row from a data table ). Okedokey, off I went and constructed the data table with full precision timestamps for every hour in the current year. Now to construct some random time ranges, I want to select the results of a random row in that table. Ah ha! 9i's analytics to the rescue.
DOH! It didn't work... without the counter-intuitive rownum restriction on dual it randomly returns no rows, multiple rows and more importanly rows that do NOT fulfil the criteria of b.n_row being equal to a.n_random_row. To get it to work I need to put the patently ridiculous ROWNUM = 1 against the DUAL inline view .... Any ideas what is going wrong?
=============== SETUP =================
create table tmp_timeline ( t_timestamp timestamp(9) with time zone );
insert into tmp_timeline
select to_timestamp_tz( '01-JAN-2002 00:00:00 +10:00', 'DD-MON-YYYY HH24:MI:SS TZH:TZM' ) + rownum / 24 t_timestamp
from all_objects, all_objects
where rownum < 8760;
=============== SETUP ====================
=============== ERRONEOUS? SQL =============
select to_char( t_timestamp ) "timestamp",
n_row,
n_random_row
from
-- ( 8759 is the count(*) of rows in table tmp_timeline )
select trunc( dbms_random.value( 1, 8759 ) ) n_random_row
from dual
-- where rownum = 1
-- ???? Uncommenting the nonsense line above this one fixes!
) a
inner join
select tt.t_timestamp,
row_number() over ( order by tt.t_timestamp ) n_row
from tmp_timeline tt
) b
on b.n_row = a.n_random_row
=============== ERRONEOUS? SQL =============
I was under the impression that DUAL is designed to return exactly ONE row. Is my understanding of INNER JOIN and DUAL somehow cockeyed or is there something weird going on with the function execution?
Please shed some light on this if you have any ideas!
Thanks,
Lachlan Pitts
[select * from v$version]
Oracle9i Enterprise Edition Release 9.0.1.1.1 - Production
PL/SQL Release 9.0.1.1.1 - Production
CORE 9.0.1.1.1 Production
TNS for 32-bit Windows: Version 9.0.1.1.0 - Production
NLSRTL Version 9.0.1.1.1 - ProductionPartition Outer Joins is the feature of Oracle 10g not 9i
i think u r confuse with Analytical Functions Partition by thing.... Analytical functions are available since 8i
Syntax for 10g Partition by
SELECT ...
FROM ...
PARTITION BY (expr [,expr ]... )
RIGHT OUTER JOIN table_referenceBaig
[My Oracle Blog|http://baigsorcl.blogspot.com/] -
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.
KyleScott,
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 -
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.
JohnAs 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'
\_(ツ)_/ -
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 $sheetnamesHere'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 -
Oracle's SQL select should have a syntax like this
Oracles SQL is very powerful but lacks a basic thing the LIMIT and OFFSET syntax which
is present in postgres sql, I recommend oracle to support this syntax in future release.
more details of this syntax can be found at :
http://www.postgresql.org/idocs/index.php?sql-select.html
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
[ FOR UPDATE [ OF tablename [, ...] ] ]
[ LIMIT { count | ALL } ]
[ OFFSET start ]I've executed the above queries against my table and the results follows :
The structure of the table
Name Null? Type
FATWAID NOT NULL NUMBER(11)
FATWASTATUS NUMBER(1)
SUBJ_NO NUMBER(4)
LANG CHAR(1)
SCHOLAR NUMBER(2)
REVIEWER NUMBER(2)
AUDITOR NUMBER(2)
PUBLISHER NUMBER(2)
SUBSCRIBER NUMBER(2)
ENTRY NUMBER(2)
FATWATITLE VARCHAR2(100)
FATWATEXT CLOB
FATWADATE DATE
TRANSLATE CHAR(1)
SELECTED NUMBER(1)
SUBJ_MAIN NUMBER(4)
I have set timing on and executed each query above, following are the statistics.
First the number of rows in the table.
SQL>set timing on
SQL>select count (*) from fatwa;
COUNT(*)
1179651
Elapsed: 00:00:13.05
The query of Andrew Clarke
SQL>SELECT fatwaid FROM (SELECT fatwaid, rownum as ranking FROM fatwa) r
WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
SQL>/
Enter value for offset: 100000
Enter value for limit: 100009
old 2: WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
new 2: WHERE r.ranking BETWEEN 100000 AND 100009
FATWAID
96592
96593
96594
96595
96596
96597
96598
96599
96600
96601
10 rows selected.
Elapsed: 00:00:12.02
SQL> /
Enter value for offset: 1000000
Enter value for limit: 1000009
old 2: WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
new 2: WHERE r.ranking BETWEEN 1000000 AND 1000009
FATWAID
994621
994622
994623
994624
994625
994626
995769
995770
995771
995772
10 rows selected.
Elapsed: 00:00:12.00
The response time is decreasing because of use of bind variables,
but 12 seconds is a sign of poor performance.
Now a slight modification to Clarke's query
I will add order by clause
SQL> ed
Wrote file afiedt.buf
1 SELECT fatwaid FROM (SELECT fatwaid, rownum as ranking FROM fatwa ORDER BY fatwaid) r
2* WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
SQL> /
Enter value for offset: 100001
Enter value for limit: 100010
old 2: WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
new 2: WHERE r.ranking BETWEEN 100001 AND 100010
FATWAID
100032
100033
100034
100035
100036
100037
100038
100039
100040
100041
10 rows selected.
Elapsed: 00:00:04.00 -- time reduced from 12 to 4 seconds
A time of 4 seconds is acceptable but not good,
response time should be in milli seconds.
SQL> /
Enter value for offset: 1000001
Enter value for limit: 1000010
old 2: WHERE r.ranking BETWEEN &OFFSET AND &LIMIT
new 2: WHERE r.ranking BETWEEN 1000001 AND 1000010
FATWAID
1000032
1000033
1000034
1000035
1000036
1000037
1000038
1000039
1000040
1000041
10 rows selected.
Elapsed: 00:00:03.09 -- this reduction is because of bind variables
The query of Chris Gates
SQL>select fatwaid
2 from ( select a.*, rownum r
3 from ( select *
4 from fatwa
5 --where x = :host_variable
6 order by fatwaid ) a
7 where rownum < &HigerBound )
8 where r > &LowerBound
SQL> /
Enter value for higerbound: 100011
old 7: where rownum < &HigerBound )
new 7: where rownum < 100011 )
Enter value for lowerbound: 100000
old 8: where r > &LowerBound
new 8: where r > 100000
FATWAID
100032
100033
100034
100035
100036
100037
100038
100039
100040
100041
10 rows selected.
Elapsed: 00:00:02.04
This seems to be fast
SQL> /
Enter value for higerbound: 1000011
old 7: where rownum < &HigerBound )
new 7: where rownum < 1000011 )
Enter value for lowerbound: 1000000
old 8: where r > &LowerBound
new 8: where r > 1000000
FATWAID
1000032
1000033
1000034
1000035
1000036
1000037
1000038
1000039
1000040
1000041
10 rows selected.
Elapsed: 00:01:14.02
but this is worst when upper bound is 1 million.
Finally Myers query
SQL> select fatwaid from
2 (select /*+ INDEX(fawtaid pk_fatwa) */ fatwaid, rownum x from fatwa
3 where rownum < &UpperBound )
4 where x > &LowerBound;
Enter value for upperbound: 100011
old 3: where rownum < &UpperBound )
new 3: where rownum < 100011 )
Enter value for lowerbound: 100000
old 4: where x > &LowerBound
new 4: where x > 100000
FATWAID
122418
122419
122420
122421
122422
122423
122424
122425
122426
122427
10 rows selected.
Elapsed: 00:00:00.03 -- too fast
SQL> /
Enter value for upperbound: 1000011
old 3: where rownum < &UpperBound )
new 3: where rownum < 1000011 )
Enter value for lowerbound: 1000000
old 4: where x > &LowerBound
new 4: where x > 1000000
FATWAID
984211
984212
984213
984214
984215
984216
984217
984218
984219
984220
10 rows selected.
Elapsed: 00:00:02.02 -- with 1 million rows also satisfactory but it is not is milliseconds
The same query after using order by clause
SQL> select fatwaid from
2 (select /*+ INDEX(fawtaid pk_fatwa) */ fatwaid, rownum x from fatwa
3 where rownum < &UpperBound ORDER BY fatwaid)
4 where x > &LowerBound;
Enter value for upperbound: 100011
old 3: where rownum < &UpperBound ORDER BY fatwaid)
new 3: where rownum < 100011 ORDER BY fatwaid)
Enter value for lowerbound: 100000
old 4: where x > &LowerBound
new 4: where x > 100000
FATWAID
100032
100033
100034
100035
100036
100037
100038
100039
100040
100041
10 rows selected.
Elapsed: 00:00:00.06
SQL> /
Enter value for upperbound: 1000011
old 3: where rownum < &UpperBound ORDER BY fatwaid)
new 3: where rownum < 1000011 ORDER BY fatwaid)
Enter value for lowerbound: 1000000
old 4: where x > &LowerBound
new 4: where x > 1000000
FATWAID
1000032
1000033
1000034
1000035
1000036
1000037
1000038
1000039
1000040
1000041
10 rows selected.
Elapsed: 00:00:07.03 -- slow
SQL> /
Enter value for upperbound: 1000011
old 3: where rownum < &UpperBound ORDER BY fatwaid)
new 3: where rownum < 1000011 ORDER BY fatwaid)
Enter value for lowerbound: 1000000
old 4: where x > &LowerBound
new 4: where x > 1000000
FATWAID
1000032
1000033
1000034
1000035
1000036
1000037
1000038
1000039
1000040
1000041
10 rows selected.
Elapsed: 00:00:00.06
when I execute the same query again it is bringing records from
the SGA so it is very fast
Now which one to choose from ?
Andrew and Myers queries are good and currently I am using
Myers query.
There should be some technique to do this in the most efficient way.
any input is appreciated. -
Picking the right values from tables - SQL (select statement)
Hi everyone,
I'm facing the litlle(?) problem in Oracle environment.
Let me explain:
I have two tables.
TABLE 1
Id1 | Val1 | Id2 | Val2
A | 44 | B | 36
B | 36 | A | 44
TABLE 2
Id | Name
A | New York
B | Seattle
I need to get from those tables, using SQL statement, result like this:
Id1 | Val1 | Name1 | Id2 | Val2 | Name2
A | 44 | New York | B | 36 | Seattle
NOTE !! Very important!! If in table 1 we have crossed the same values in fields IdX and ValX in two rows (like in example)- just one of them should be presented as a result.
I'm afraid it's a bit too complex. You, guys are my last hope.
Looking forward for any solutions.
Thanks in advance!jeneesh wrote:
This can give you a startJaneesh, the OP specified that the duplication was across the ID and the VAL columns, but your solution only checks the ID's..
SQL> ed
Wrote file afiedt.buf
1 with t1 as (select 'A' as id1, 44 as val1, 'A' as id2, 36 as val2 from dual union all
2 select 'A', 36, 'A', 36 from dual)
3 ,t2 as (select 'A' as id, 'New York' as name from dual union all
4 select 'B', 'Seattle' from dual)
5 -- END OF TEST DATA
6 select distinct greatest(id1,id2) id1,
7 case when id1 > id2 then val1 else val2 end val1,a.name name1,
8 least(id1,id2) id2,
9 case when id1 < id2 then val1 else val2 end val2,b.name name2
10 from t1 t,t2 a,t2 b
11 where greatest(id1,id2) = a.id
12* and least(id1,id2) = b.id
SQL> /
I VAL1 NAME1 I VAL2 NAME2
A 36 New York A 36 New York
SQL>With this data I would have expected both rows to be returned as there is a difference in the val columns..
SQL> ed
Wrote file afiedt.buf
1 with t1 as (select 'A' as id1, 44 as val1, 'A' as id2, 36 as val2 from dual union all
2 select 'A', 36, 'A', 36 from dual)
3 ,t2 as (select 'A' as id, 'New York' as name from dual union all
4 select 'B', 'Seattle' from dual)
5 -- END OF TEST DATA
6 ,t3 as (select distinct id1, val1, id2, val2
7 from
8 (
9 select decode(switch,1,id2,id1) as id1
10 ,decode(switch,1,val2,val1) as val1
11 ,decode(switch,1,id1,id2) as id2
12 ,decode(switch,1,val1,val2) as val2
13 from (select id1, val1, id2, val2
14 ,case when id1||val1 > id2||val2 then 1 else 0 end as switch
15 from t1)
16 )
17 )
18 --
19 select t3.id1, t3.val1, t2_1.name
20 ,t3.id2, t3.val2, t2_2.name
21 from t3 join t2 t2_1 on (t2_1.id = t3.id1)
22* join t2 t2_2 on (t2_2.id = t3.id2)
SQL> /
I VAL1 NAME I VAL2 NAME
A 36 New York A 36 New York
A 36 New York A 44 New York -
Can we convert a SQL (Select Statement) to Procedure.?
Hi
I am using a select sql for retrieving the results - Below is a sample sql select query.
select TableC.DATEFIELD as QUERY_DATE,
TableB.COLUMN1 PROCESS,
TableC.COLUMN1 PRODUCT,
sum(TableC.COLUMN4) as OPEN_INSTANCES
from TableA, TableB, TableC
where TableB.COLUMN1 = TableA.COLUMN2
and TableA.COLUMN2 = TableC.COLUMN2
and DATEFIELD <= to_date('2011-02-02' ,'YYYY-MM-DD')
and DATEFIELD >= to_date('2011-02-02' ,'YYYY-MM-DD')
and TableC.COLUMN4 <= (24 * 3600 )
and TableB.COLUMN1 like 'PROCESSID'
and TableC.COLUMN1 in ('OSRCITR')
group by TableC.DATEFIELD as QUERY_DATE,
TableA.COLUMN1 PROCESS,
TableC.COLUMN1 PRODUCT
I believe if we use a Procedure, It would be much faster. Is there any way that we can convert the above select sql to a procedure. If yes, how can it be.
Thanks in Advance.
-SreekantSreekant wrote:
select TableC.DATEFIELD as QUERY_DATE,
TableB.COLUMN1 PROCESS,
TableC.COLUMN1 PRODUCT,
sum(TableC.COLUMN4) as OPEN_INSTANCES
from TableA, TableB, TableC
where TableB.COLUMN1 = TableA.COLUMN2
and TableA.COLUMN2 = TableC.COLUMN2
and DATEFIELD <= to_date('2011-02-02' ,'YYYY-MM-DD')
and DATEFIELD >= to_date('2011-02-02' ,'YYYY-MM-DD')
and TableC.COLUMN4 <= (24 * 3600 )
and TableB.COLUMN1 like 'PROCESSID'
and TableC.COLUMN1 in ('OSRCITR')
group by TableC.DATEFIELD as QUERY_DATE,
TableA.COLUMN1 PROCESS,
TableC.COLUMN1 PRODUCT
I believe if we use a Procedure, It would be much faster. Is there any way that we can convert the above select sql to a procedure. If yes, how can it be.Using the code tags would make the query easier to read :)
What version of Oracle are you on?
Under the right conditions deconstructing a huge query into smaller components sometimes can offer performance increases, but this is more true of older versions of Oracle than recent ones. Lately I get better results from tuning queries in place - as Aman pointed out you introduce context switching (moving between the SQL and PL/SQL engines to do work) which can also hurt performance.
Try tuning the query first. Get an execution plan. Things you can look for include
* make sure the driving table is the best one
* are the join columns properly indexed? Are existing indexes being suppressed due to the functions?
Is "and TableB.COLUMN1 like 'PROCESSID' " correct? without a wildcard LIKE should evalate to =
Maybe you are looking for
-
Installing new HP Officejet Pro 6830 e-All-in-One series
We just installed the HP Officejet Pro 6830 e-All-in-One Series. The screen on the printer does nothing but spin around with the notation that it is "Checking for printer updates". Why is this happening? Like I said, we just set it up and I am tu
-
How to download photos from icloud photo stream..?
I cannot download full photos that i have in my iphone photo stream to my PC. I can only download which is uploading to photostream in the current day only. I have more than 200 images in photostream and I can download only 15 of them which is upload
-
Hi, I want to know how can we find out the open transactions in GL for Balance sheet items. e.g. If there is a loan item is available in Balance sheet and there are regular transactions happens then how can I find out which are the line items relate
-
Employee / customer replication
Hi! My ECC has customers that are also employees (so they were created in KNA1 with the same number as in the PA01 transaction - the HR master data record). The employees were replicated into CRM using ALE (SAP standard procedure) and were saved in C
-
I have just bought this phone and started using it but it seem to have a weak network signal strength I am in UK on O2 and in some areas have have low or no signal. When at home I have only 1 bar showing and sometimes no signal but a Nokia 7230 a