Reusing query results in PL/SQL
I have a procedure in a package that I want to query several times using the analytical function row_number to get, say, the 5th row and the 95th row:
select days_missed_negative_is_late
into l_5pct
from (select days_missed_negative_is_late,
row_number() over(order by days_missed_negative_is_late asc) rn
from (*some complicated query*)
order by days_missed_negative_is_late))
where rn = 5;
then I do the whole thing again, except the last line reads "rn=95". This seems inefficient. I would like to build the results one time then query it twice:
select days_missed_negative_is_late
into l_5pct
from something
where rn = 5;
select days_missed_negative_is_late
into l_5pct
from something
where rn = 95;
or the equivalent functionality, of course. Again, this is in a PL/SQL package. Any ideas of the best way to build the results and read them several times?
Here is an example.
1 select object_name from
2 (select object_name,row_number() over(order by created) rn
3 from all_objects
4 where rownum<101)
5* where rn in(5,95)
SQL> /
OBJECT_NAME
I_CON2
DEPENDENCY$
You could for example 1) use a cursor and loop or
2) select and bulk collect.
I hope this helps.
Similar Messages
-
How to view complete date stamp in query result view in sql developer?
Hi,
In the query result, the date present in db is shown as DD-MM-YYYY format but I want to view the complete date stamp. When I view the same data in aqua data studio, I see the complete time stamp. Please let me know if I need to do some settings in Oracle SQL Developer so that complete date is shown?
How to view complete date stamp in query result view in sql developer?
Thanks in advance,
Vineet864793 wrote:
Hi,
In the query result, the date present in db is shown as DD-MM-YYYY format but I want to view the complete date stamp. When I view the same data in aqua data studio, I see the complete time stamp. Please let me know if I need to do some settings in Oracle SQL Developer so that complete date is shown?
How to view complete date stamp in query result view in sql developer?
Thanks in advance,
VineetAlternatively you can execute below
set nls_date_format='DD-MM-YYYY HH24:MI:SS';Regards,
Achyut K -
Query output similar to sql plus results
Is it possible to configure SQLDeveloper to output the query result similar to sql plus ?
I want to print the field names of the sql input, something as:
OWD_ID seconds policies/s COUNT(OWD_ID) MIN(OWE_PRC_DT) MAX(OWE_PRC_DT)
5174 872 17 14892 06/11/2009 12:53:31 06/11/2009 13:08:03 Thanks
Claudio
Edited by: Claudio Miranda on Nov 10, 2009 11:49 AM
Edited by: Claudio Miranda on Nov 10, 2009 11:51 AMClaudio Miranda wrote:
Is it possible to configure SQLDeveloper to output the query result similar to sql plus ?
I want to print the field names of the sql input, something as:
OWD_ID seconds policies/s COUNT(OWD_ID) MIN(OWE_PRC_DT) MAX(OWE_PRC_DT)
5174 872 17 14892 06/11/2009 12:53:31 06/11/2009 13:08:03 Thanks
Claudio
As far as I know, no :( -
Query Result pane - disabling tooltip display of LOB data
In the query result pane of SQL Developer, if a column is too long for the display (typically, in my case, for a CLOB column) and you hover the mouse over the column data, a tooltip showing the full value appears.
For an example, do "select sql_fulltext from v$sql where rownum < 3" and hover the mouse over one of the values in the SQL_FULLTEXT column.
In our application we typically query a table with a large CLOB column, and the tooltip fills the whole screen. This is a pain if you just leave your mouse on the screen somewhere over a CLOB column while typing :-( I've looked for a way to switch off this tooltip, but haven't managed to find one. Can anyone point me at a way of doing so? Unfortunately, I'm running SQL Developer 2.1.1, but even a response along the lines of "you can only do this in 3.0 and later, and this is how" would be useful, as it might help me argue for an upgrade.
Thanks,
PaulHi Paul,
Actually versions 3.0 and 3.1 have a very nice UI (Tools | Preferences | Mouseover Popups) to control this sort of thing, but unfortunately the settings seem only applicable to the debugger.
You might consider making a feature request for this on the SQL Developer Exchange.
Regards,
Gary
SQL Developer Team -
Use the results of an SQL query to create another query
I am working on a bidding/allocation system using C# and MySQL, and I am currently having difficulty implementing the “post-allocation” mechanics of the system. Let me explain how it works, before introducing the code:
When the bids are made on the system, they all have the position 0, so the first thing the system does is order them according to priority.
(bid table)
In this case, 5 bidders are interested in what is in plot 15, but we have not assigned them a position yet.
(bid table)
The system then organises the bids according to the order in which they are going to processed.
The bids are then allocated, but unfortunately there are only 3 spaces in plot 15 that can be allocated. As a result, we use the priority listing to determine which bidder gets what.
(booking table)
At this stage, I can say that I am stuck, there are two things that I want to do, both of which involve reusing the results of the query at step 2.
(bid table)
The bidders that have their job allocated should see: their bid.status updated
from Queued to Allocated,
the bid.position should
be set to 0,
and their job_id should
be set to the booking they have been allocated (i.e. booking.id).
The bidders that have not had their jobs allocated should see: their bid.status remain
as Queued, and their bid.position should
be set to 0 in
preparation for the method to run again
The difficulty I am having is in stage 3, how do I determine which jobs have been allocated and which ones have not, and then run the necessary SQL queries in order to make the updates?
My code so far is as follows:
// STEP 1a - SELECT BIDS
string query =
"SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
"JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode=@postcode " +
"ORDER BY t2.market_access ASC, t1.datetime ASC";
var bidList = new List<BidList>();
var cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
var item = new BidList
OperatorId = dataReader["operator_id"] + "",
PlotId = dataReader["plot_id"] + "",
Position = dataReader["position"] + "",
Datetime = dataReader["datetime"] + "",
MarketAccess = dataReader["market_access"] + "",
bidList.Add(item);
dataReader.Close();
// STEP 1b - SET PRIORITIES
for (var i = 0; i < bidList.Count; i++)
var position = i + 1;
bidList[i].Position = position.ToString();
query = "UPDATE bid SET position=@position WHERE status='Queued' AND postcode=@postcode AND operator_id=@operator_id;";
cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@position"), position);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
cmd.Parameters.AddWithValue(("@operator_id"), bidList[i].OperatorId);
cmd.ExecuteNonQuery();
dataReader.Close();
// STEP 2 - ALLOCATE JOBS ACCORDING TO PRIORITY
foreach (var t in bidList)
query = "SELECT operator_id, plot_id, status FROM booking " +
"WHERE status='open' AND postcode=@postcode AND operator_id='0'" +
"ORDER BY datetime ASC;" +
"UPDATE booking SET operator_id=@operator_id, status='Allocated' " +
"WHERE (plot_id=@plot_id AND operator_id='0' AND status='Open') LIMIT 1;";
cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@operator_id"), t.OperatorId);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
cmd.Parameters.AddWithValue(("@plot_id"), t.PlotId);
cmd.ExecuteNonQuery();
dataReader.Close();
// STEP 3
CloseConnection();I can't tell. When modifying row(s) you have to be able to uniquely be able to identify the row(s) in the database you want to modify. That is why I recommended the other day to use DataAdapter instead of the DataReader. You can with the
reader, but you need to unique identify the rows.
I can't tell from the limited amount of data you posted if in table 2 that there is only one row with the same operator id and plot id. It looks like in table 2 the 'id' number is unique. When working with a database with multiple tables you
need to be able to link tables together with primary keys (columns wit unique values). If the database isn't designed properly then it is impossible to do some operations. So you always have to make sure you design a database properly.
jdweng
When you say table 2 are you referring to the bid or booking table?
Here is the table structure for the bid table
Here is the table structure for the booking table
Hope it helps makes things clearer! -
Getting query results from a PL/SQL procedure
Hi! So, I’m a little stumped and I can’t seem to find the answer to what I believe is probably a simple question…
So, here goes… I have a big ol’ union query that I use to create a report on a page, it’s about 25k – not over the 32k limit, but fails to be able to compile every time (I always get a 400 – Bad Request error). I’m not sure why this is happening, but I can remove a union statement and it compiles just fine – so it has something to do with the size of the query. ANYWAY – I’ve resolved that I should put this bad boy into the database as a stored procedure and just call it from Apex, my problem is I can’t figure out quite how to do this with variables, etc.…
Instead of giving you my whole big query, I’ll use the emp table as the concept is the same:
Say we have a query that creates a report on a page:
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where job = :P_JOB
and hiredate >= :P_HIREDATE;
How would I take this query, create it as a stored procedure on the db, pass the variables from Apex and return the query result set from the stored proc as a report?
I really appreciate any help on this!
Best,
GilcrestHi Gilcrest,
You should create the query as a View and use the view name and the WHERE clause in the report's sql source.
Andy -
Sending email using PL/SQL based on a query result
Hello all,
I want to create a procedure using PL/SQL, based on a query result.Here is the scenario:
I have multiple tables in Target and Source databases that I want to compare(not the whole table but queries on these tables) and if they differ, I want to shoot an email. I have some ideas how to implement this but not sure whether it is the best approach.
select Acct_id, total from SourceTableA
minus
select Acct_id, total from TargetTableA
select Acct_id, sum from SourceTableB
minus
select Acct_id, sum from TargetTableB
If the result of any of above queries > 0 then I want to shoot an email and want to repeat this procedure in the morning every day.
I know how to implement send_mail procedure using UTL_SMTP package and how to schedule tha job by dbms_job package. But I am not sure how to implement the result of minus query. In case if minus > 0 then I also want to send the name of tables in the email message where source and target tables are not same. Should i use cursor, variable or insert the result in a new table? any help would be highly appreciated. Thanks in advance.
KhanActually these queries are the part of our daily testing that we run everyday manually(after the scheduled ETL load) to see if there are any discrepencies between our datawarehouse tables and source tables. So instead of running these queries manually everyday we want to schedula a procedure that will shoot an email in case of any discrepency and indicate which tables have problems.
-
I tried to make the question as explicit as possible.
Refer to Sql Server Management Studio's Results view. Depending upon the structure of the execution plan, the Results pane may begin displaying results while the query is still executing. Can someone point me in a direction for architecting a
data layer (I am tech and framework agnostic for this task. Any solution will suffice) that will begin receiving pages of the set before SQL Server has completed the entire query?
The call from the data layer to SQL Server will obviously have to be asynchronous, but is there any additional ceremony that I need to be aware of when issuing OPTION (FAST x) to the query optimizer?Thanks for the reply. (I actually meant to put this in the SQL Data Access forum, not the T-SQL forum)
"Generally the last step is ORDER BY in a
query, so nothing can start before that executes."
I would imagine you cannot ORDER BY and yield results as they are fetched because of the execution plan that would be generated. For the purposes of this post, please assume that sorting will be done purely client side
"Can you post your query?"
For purposes of discussion, let's assume that the query is
select *
from information_schema.columns
and also assume that you have "lots" of columns to display.
This was an exploratory question to see what would be necessary to replicate the behavior of Management Studio's Query Result view in a custom application.
I would imagine that there's going to be a lot of analysis of the execution plans that get generated in order for the OPTION (FAST x) optimizer hint to do any good, but apart from general tuning concerns that would allow SQL SERVER to yield a page of data
"fast", I was wondering if there was anything else required of the calling client to force it to yield return its first page.
After thinking about this (and phrasing it the way I did in the last sentence) perhaps this is the incorrect forum for this question. I imagine that my concerns are better addressed in forums dedicated to the technology of the calling client (which
would be a .NET assembly)
Be that as it may, if there is any ceremony that SQL Server imposes on clients in order to yield return, I would expect that my question would be in the scope of SQL Server discussions (even though I intended this to be in a different SQL Server forum) -
Xml parsing error while selecting whole result set for sql query
Hi All,
I am having xml parsing error while selecting whole query result set. The data is coming fine for default result set of 50 rows.
My exception is below.
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00234: namespace prefix "xsi" is not declared
Error at line 1
ORA-06512: at "SYS.XMLTYPE", line 254
ORA-06512: at line 1
*31011. 00000 - "XML parsing failed"*
**Cause: XML parser returned an error while trying to parse the document.*
**Action: Check if the document to be parsed is valid.*
My sql query is below that is giving results for default result set of 50 rows.
select extract(xmlType(clob_xml_colm_name), '//v2:node1//childnode/text()','xmlns:v2="namespace_url"').getStringVal() from table_name
My sql developer version is below.
Java(TM) Platform 1.7.0_04
Oracle IDE 3.1.07.42
Versioning Support 3.1.07.42
My database version is below.
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bit
Please could any one help me urgently as the sql query is supposed to be correct as it is returning query results, but the problem happening when i try to select whole result set.
Thanks and regards,What does the XML look like? It appears that some of the supposed XML stored as a CLOB is not really valid XML. Find the row in the table that is causing your issue and review the "XML" in it.
-
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 -
2.1.0.62: Exporting query results does not work if SQL has a join
I get an error message, when I try to export the following test case to any data format.
create table test1 (id number(2), text varchar2(5));
create table test2 (id number(2), text varchar2(5));
insert into test1 values (1,'test');
insert into test2 values (1,'test');
select t1.*
from
test1 t1,
test2 t2
where
t1.id=t2.id;
I try to translate my german error message to english:
"There are no valid columns for export available. Clob- or Blob-Columns are currently not supported"
I get this message, when I right click into the query result grid and select export and then any data format.
Hope that is not a double post but searching for export did not find results for 2.1.
The following SQL also produces the error:
select t1.* from test1 t1;
These SQLs can be exported though:
select * from test1 t1;
select t1.id from test1 t1;
I should have mentioned that I work with Windows XP and Oracle 10.2.0.4.
Regards,
dhalek
Edited by: dhalek on Oct 13, 2009 5:04 PMHi,
Dhalek.
I've got the same problem here.
In my SQL Dev, I disabled the Autopopup code completion insight in SQL Worksheet. (Tools - Preferences - Code Editor - Code Completion - untick the checkbox). Restart SQL Dev. Tried to export a query.
The same error message appears.
My workaround is to re-enable the autopopup and restart SQL Dev.
The disabled autopopup code completion insight caused me these
2.1 EA1: Bugs - cannot Export Data from Grid
2.1 EA2: Bugs on code completion for displaying column name
Hope this helps,
Buntoro -
Result of an SQL query as a Column name of another query
Hi Friends,
Can we use a result of a SQL Query as a column name of another table to retrieve data. If so please help me.
For eg :
I have a table where is store numbers;
select col1 from table1 where col1='5';
and i have another table where .. this value of col is a column name..
select ( select col1 from table1 where col1='5') from table2;
Thanks in advance.Hi,
ORAFLEX wrote:
Hi Friends,
Can we use a result of a SQL Query as a column name of another table to retrieve data. If so please help me.
For eg :
I have a table where is store numbers;
select col1 from table1 where col1='5';
and i have another table where .. this value of col is a column name..
select ( select col1 from table1 where col1='5') from table2;
Thanks in advance.Do you really mean that?
select col1 from table1 where col1='5';That query will always return either '5' or nothing. Whatever you're trying to accomplish with that, you can do with an EXISTS query.
Perhaps you meant to reference two different columns in that query:
select col1 from table1 where col2='5';In that case, sorry, no, you can't do that without resorting to dynamic SQL.
If the same column is used throughout the query (but could change every time you run the query), then the dynamic SQL might be pretty easy. In SQL*Plus, for example, you could use substitution variables, defined in another query at run-time.
If there are only a few possible values that the sub-query could possibly return, and you know what they all are, then you can fake a dynamic query like this:
SELECT CASE ( SELECT col1
FROM table1
WHERE col2 = '5'
WHEN 'BONUS' THEN bonus
WHEN 'COMM' THEN comm
WHEN 'SAL' THEN sal
END AS col1
FROM table2
;Sorry to give such a vague answer, but it's the best I can do with the information I have.
It would help if you posted a little sample data (CREATE TABLE and INSERT statments for both tables), and the results you want to get from that data. If you want to pass a parameter to the query, give the results you want for a couple of different parameters. -
Hiding SQL statement in Query Result Window
Hi everyone,
Is it possible to hide the SQL statement from a query result window? This can usually be done by click the orange triangle that is positioned to the left of the SQL string box (to expand and collapse it). The System Queries have this box collapsed per default, is it possible to have this setup as default for all queries, including the custom? If so, please let me know where this can be done.
CheersYou should do this only with SDK programming - dont allow to show the syntax. The next, but problematic way, is the code you have do inside stored procedure and call only this sp inside the query generator window - if you have there some input parameters, you should use filling variables before executing sp and get it as input parameters to sp.
-
Emailing results of a SQL Query....
I am new to Oracle and was wondering if there is a way to create an email task that could be used to email results of a sql query. My query returns emails addresses that meet a specified criteria. I want to use an email task that takes these addresses as variables and sends out an email to the specified email address.
Anyone provide any help with how I might do this?
Thanks.Hi,
The odiSqlUnload has a "select" command. Is possible, at your process, work with the "LPAD()" and/or "RPAD()" function to complete the necessary whitespace at each column?
To the column heading I suggest you use the "union" like: (I put the lpad and rpad fuctions as example...)
select col1, col2, col3
from(
select 1 as internal_order, 'header_col1' as col1, 'header_col2' as col2, 'header_col3' as col3
from dual
UNION
select 2 as internal_order, RPAD(col1, 10, ' ') as col1 , LPAD(col2, 50, ' ') as col2 , col3
from your_table)
order by internal_order
Do you think this will work for you? -
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 JudgeHi 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
Maybe you are looking for
-
Dsml and SQL 2005 reporting services?
I usually post over in the IDM forum so be nice to the newbie here :) I have a Sun Directory server that I've enabled DSML on. On that side everything is good. However, ideally I want to pull this data into a MS SQL 2005 reporting services report. Th
-
How do I set up my laptop to view activity in home while gone?
I would like to use my Mac book pro to monitor activity in my home while I am gone. How do I set it up?
-
Best export method of footage from Final Cut Express to DVD?
I'm exporting footage from Final Cut Express using Quicktime Player and then burning the footage to DVD using iDVD. The end result on DVD has very jagged interlacing (or noise) on objects in motion which aren't present when viewing the footage on FC.
-
Nokia lumia 520 and 525 support touch to focus?
Do the above phones support touch to focus?
-
Photoshop CS6 requires serial number
Hi, I have purchased and used Creative Cloud without problems since May. Today PS asked me to enter a serial number (via AAM) which I have found in the "My Products" section in my Adobe Account. The serial number listed there doesn't work, and I don'