PL/SQL how to loop thru SQL statement?
Hey guys. I have this bit of a complicated problem.
I have a cursor that selects a DISTINCT field called Term and a StudentID.
I am looping thru that cursor.
Inside that loop I have another SQL statement that is pulling all rows from the DB where the Term = the Term and the StudentID= the StudentID from the crusor loop.
My problem is how do I get all the information/rows returned from that SQL statement? I need to loop thru it somehow, but I am not sure how to do it.
If there is a better way to get this done feel free to chime in.
Here is my code.
/* CURSOR*/
CURSOR c_GPAPerTerm IS
SELECT DISTINCT Term, Student_ID FROM course_grades
WHERE STUDENT_ID = p_StudentID;
/* OPEN AND LOOP THRU CURSOR*/
OPEN c_GPAPerTerm;
LOOP
FETCH c_GPAPerTerm INTO v_Terms,v_StudentID;
/* SQL STATEMENT NEED TO LOOP THRU AND GET VALUES FOR EACH ROW*/
SELECT Score
INTO v_Scores
FROM course_grades
WHERE Term = v_Terms and StudentID = v_StudentID;
EXIT WHEN c_GPAPerTerm%NOTFOUND;
END LOOP;
CLOSE c_GPAPerTerm;
Ok here's my complete code....it's pretty big though...hope it's not too confusing.
It compiles fine if I take the new cursor out, so the error is somewhere in that cursor.
CREATE OR REPLACE PROCEDURE get_Student_GPA(p_StudentID IN NUMBER) AS
/*VARIABLES*/
v_Terms VARCHAR2(6);
v_Courses VARCHAR2(6);
v_Scores NUMBER;
v_Grade CHAR;
v_GPA NUMBER;
v_ScoresTotal NUMBER :=0;
v_StudentID NUMBER;
/*CURSORS*/
CURSOR c_GetTerms IS
SELECT Term
FROM course_grades
WHERE STUDENT_ID = p_StudentID;
CURSOR c_GetCourseAndGrade IS
SELECT Course_ID, Score FROM course_grades
WHERE STUDENT_ID = p_StudentID;
CURSOR c_GPAPerTerm IS
SELECT DISTINCT Term, Student_ID
FROM course_grades
WHERE STUDENT_ID = p_StudentID;
CURSOR c_GetScores (p_Term VARCHAR2, p_StudentID NUMBER) IS
SELECT Score
FROM course_grades
WHERE Term = p_Term AND StudentID = p_StudentID;
/*FUNCTIONS*/
FUNCTION convert_grade(p_GradeNumber IN NUMBER)
RETURN CHAR IS
BEGIN
/* GET NUMERIC GRADE AND CONVERT TO LETTER */
CASE
WHEN p_GradeNumber < 60 THEN RETURN 'F';
WHEN (p_GradeNumber > 59 AND p_GradeNumber < 70) THEN RETURN 'D';
WHEN (p_GradeNumber > 69 AND p_GradeNumber < 80) THEN RETURN 'C';
WHEN (p_GradeNumber > 79 AND p_GradeNumber < 90) THEN RETURN 'B';
WHEN (p_GradeNumber > 89 AND p_GradeNumber < 101) THEN RETURN 'A';
ELSE RETURN 'Z';
END CASE;
END convert_grade;
FUNCTION calculate_gpa(p_TotalHourPoints IN NUMBER, p_TotalHours IN NUMBER)
RETURN NUMBER IS
/*CREATE VARIABLE TO HOLD GPA*/
v_GPA NUMBER;
BEGIN
/*CALCULATE AND OUTPUT GPA*/
v_GPA := p_TotalHourPoints/p_TotalHours;
RETURN v_GPA;
END calculate_gpa;
FUNCTION calculate_point (p_Grade IN CHAR)
RETURN NUMBER IS
BEGIN
/* GET LETTER GRADE AND CONVERT TO NUMBER */
CASE
WHEN p_Grade = 'A' THEN RETURN 4;
WHEN p_Grade = 'B' THEN RETURN 3;
WHEN p_Grade = 'C' THEN RETURN 2;
WHEN p_Grade = 'D' THEN RETURN 1;
WHEN p_Grade = 'F' THEN RETURN 0;
ELSE RETURN 0;
END CASE;
END calculate_point ;
/****BEGIN MAIN BLOCK********/
BEGIN
DBMS_OUTPUT.PUT_LINE('**********TERMS**********');
OPEN c_GetTerms;
LOOP
FETCH c_GetTerms INTO v_Terms;
DBMS_OUTPUT.PUT_LINE('Term: ' || v_Terms);
EXIT WHEN c_GetTerms%NOTFOUND;
END LOOP;
CLOSE c_GetTerms;
DBMS_OUTPUT.PUT_LINE('**********COURSES AND GRADES**********');
OPEN c_GetCourseAndGrade;
LOOP
FETCH c_GetCourseAndGrade INTO v_Courses, v_Scores;
v_Grade := convert_grade(v_Scores);
DBMS_OUTPUT.PUT_LINE('Course: ' || v_Courses || ' Grade: ' || v_Grade);
EXIT WHEN c_GetCourseAndGrade%NOTFOUND;
END LOOP;
CLOSE c_GetCourseAndGrade;
DBMS_OUTPUT.PUT_LINE('**********GPA PER TERM**********');
OPEN c_GPAPerTerm;
LOOP
FETCH c_GPAPerTerm INTO v_Terms,v_StudentID;
/*NEW CURSOR LOOP WILL GO HERE*/
v_ScoresTotal := v_ScoresTotal + v_Scores;
v_GPA := calculate_gpa(v_ScoresTotal, 3);
v_ScoresTotal :=0;
DBMS_OUTPUT.PUT_LINE('Term: ' || v_Terms || ' GPA: ' || v_GPA);
EXIT WHEN c_GPAPerTerm%NOTFOUND;
END LOOP;
CLOSE c_GPAPerTerm;
END get_Student_GPA;
/
Similar Messages
-
This is my first pl/sql program, I've written psudocode on paper, but not sure what to do for two parts.
What I'm trying to do is write pl/sql that will check a row based on an employee id #.
declare
cursor cur is
select *
from employee
where employee_id = foo;What we are checking are the results the employee answered. They have answered 180 questions and I want to find when the answer a 0, 7, and 9.
Basically the pl/sql has to loop thru the 180 questions
loop
v_count := vcount + 1
select *
from employee
where q1 thru q180 in (0, 7, 9);
end loop;
dbms_output.put_line ('Employee ID' || employee_id);
dbms_output.put_line ('Q1 - Q180' || q1 - q180); I'm not sure how to write the pl/sql to loop thur all 180 questions.
I'm not sure how to display the output to show what question they scored a 0, 7, and/or a 9 on.
thanks
Message was edited by:
cmmiller536 columns in one table? Yowsa. Without a normalized table, you are going to need dynamic pl/sql and a messy solution.
I would rethink your design, and come up with something more like so:
employee
questions
employee_responses
So that would you could easily do something like this:
declare
cursor c1 is
select ers.question_id,
que.question_name,
ers.rating
from employee emp,
questions que,
employee_responses ers
where emp.employee_id = ers.employee_id and
que.question_id = ers.question_id and
emp.employee_id = v_employee_id and
ers.rating in (0, 7, 9) and
que.enabled_flag = 'Y';
begin
for r1 in c1 loop
dbms_output.put_line('Question: '||r1.question_name);
dbms_output.put_line('Employee Rated this: '||r1.rating);
end loop;
end;Thats how I would do it - I think you are going down the wrong path. What happens if you need to create a new question or delete one? You constantly have to modify the table. Hope this helps -
how to Loop thru the RFC model
for(int i=0;i<wdContext.nodeEx_Org_Units().size();i++){
//how to get the attribute each and every columns
//mgr.reportSuccess("id" +nodeEx_Org_Units().getId());
Message was edited by:
yzme yzmeHi,
When there is a RFC Model with table ouptut....every row in the table can be correlated to elements in the model node...
your model node : <i>nodeEx_Org_Units</i>
Now if you have 5 rows as output after executing the model...there will be 5 elements created under the node. Loop through all the elements and use the get methods as given below:
// assuming tht u have two columns(attributes) <i>col1 & col2</i>
// access the node
IPrivate<view>.IEx_Org_UnitsNode tableNode = wdContext.nodeEx_Org_Units();
// access the element under the node, do not initalize this element
IPrivate<view>.IwdContext.nodeEx_Org_UnitsElement tableElem;
//loop thrugh the elements
for(int i=0; i<tableNode.size(); i++)
tableElem = tableNode.getEx_Org_UnitsElementAt(i);
// access the attributes col1 & col2
tableElem.getCol1();
tableElem.getCol2();
Regards
Srikanth -
How to loop a sql insert?
I have an ASP Survey that pulls questions from a sql
database. The results table to store the answers is simple. It has
a ResultID, QID, and Answer field.
Since the survey is dynamically built, the number of
questions in each survey is limitless. Thus my problem. How do I
construct an insert sql statement to loop thru and add a value to
the db for QID?There is a tutorial on www.charon.co.uk that may be of some
use for you as
it is written for asp
Paul Whitham
Certified Dreamweaver MX2004 Professional
Adobe Community Expert - Dreamweaver
Valleybiz Internet Design
www.valleybiz.net
"Lucky Kitty" <[email protected]> wrote in
message
news:f2f1tk$kvg$[email protected]..
>I have an ASP Survey that pulls questions from a sql
database. The results
> table to store the answers is simple. It has a ResultID,
QID, and Answer
> field.
>
> Since the survey is dynamically built, the number of
questions in each
> survey
> is limitless. Thus my problem. How do I construct an
insert sql
> statement to
> loop thru and add a value to the db for QID?
> -
How to Loop thru a Queue?
I have a Queue that I can add and remove items from, but I need to display all the contents currently in the Queue.
How would I loop thru the Queue and do this?
Any simple example will do.
Thanks!Thanks for the link. It showed me which methods an Iterator has, but not practical way to use it. So I did some googling and found this example.
import java.util.Iterator;
import java.util.NoSuchElementException;
for ( Iterator iter = myList.iterator(); iter.hasNext(); )
String key = (String) iter.next();
System.out.println( key );
}Which makes perfect sense. However, where it says Iterator iter = myList.iterator(); I am not sure what to put in the myList.iterator(); part.
I would assume that my Queue object would be used there, however, my Queue object has no .iterator() method.
Like I said, I am new to Java so this is not as easy to me as it seems it should be.
But there is all of my code if it helps.....I'll leave out the unimportant parts.
Queenode class........................................
public class QueueNode {
//fields
Object info;
QueueNode link;
public QueueNode() {
public QueueNode(Object item) {
info=item;
link=null;
public QueueNode(Object item, QueueNode qn) {
info=item;
link=qn;
}//end classQueue class..............................................
public class Queue {
//create a front and back node
private QueueNode front;
private QueueNode rear;
private int size;
//methods
public void insert(Object item){
//if queue is empty front and rear are same
if(isEmpty()){
rear=new QueueNode(item);
front = rear;
}//end if
//otherwise queue not empty add top end
else{
rear.link= new QueueNode(item);
rear=rear.link;
}//end else
///either case incriment size
size++;
}//end insert
public Object remove(){
//create a temp node referencing the front
QueueNode oldFront=front;
//peek at front item
Object item = peek();
//make front to link with the next node
front=front.link;
//remove temp node
oldFront=null;
//decrement size
size--;
//return the item that was removed
return item;
}//remove
public Object peek(){
if(isEmpty()){
throw new NullPointerException();
}//end if
else{
return front.info;
}//and else
}//end peek
public boolean isEmpty(){
return(size==0);
}//end isEmpty
public int getSize(){
return size;
}//end getsize
}//end classAnd finaly my class to test that the Queue is working....................
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class QueueTest extends JFrame implements ActionListener{
//Create Queue object
Queue q = new Queue();
public QueueTest(){
//Add title to window
super("Testing Queue's");
}//end constructor
public void actionPerformed(ActionEvent event){
if (event.getSource()==btnAddQueueItem){
q.insert(txtAddQueueItem.getText());
for(Iterator iter = q.?????; iter.hasNext();){
///Output each queue item here........
}//end for
}//end if
if (event.getSource()==btnRemoveQueueItem){
q.remove();
}//end if
}//end actionPerformed
public static void main(String[] args) {
QueueTest testQueue = new QueueTest();
}//end main
}//end class -
I have a merge statement, this executes for all the rows when the procedure is executed. Here i would like to include this merge statement as the part of LOOP so that all records will not get updated for a one time.
how can i change this merge statement to include as the part of LOOP here.
the user id should be the key to update the table USERS in merge statement, the same user id is exists in the bulk collect too..
BEGIN
v_sysdate:= pkg_utilities.fn_sysdate(1) ;
o_Error_Text := 'ORA-Error in updating end date in user_status table ';
tname:= 'user_status';
MERGE INTO user_status r1
USING (
SELECT rowid rid , lead(start_period) OVER (PARTITION by user_id
order by start_period)- 1 new_enddate FROM user_status ) r2
ON ( r1.rowid = r2.rid )
WHEN MATCHED THEN
UPDATE SET end_period = new_enddate ;
OPEN generic_cv4
FOR SELECT
user_id,user_status_type_id
FROM user_status
WHERE end_period IS NULL;
LOOP
FETCH generic_cv4 BULK COLLECT INTO
v_user_id_seq,
v_user_status_new
LIMIT p_array_size;
EXIT WHEN v_user_id_seq.COUNT = 0;
IF v_user_id_seq.COUNT > 0 THEN
o_Error_Text := 'ORA-Error in update user_status type id in users table ';
tname:= 'users';
FORALL I IN v_user_id_seq.FIRST..v_user_id_seq.LAST
UPDATE users
SET user_status_type_id = v_user_status_new(i),
last_upd_date = v_sysdate
WHERE user_id = v_user_id_seq(i);
END IF;
COMMIT;
END LOOP;
v_user_id_seq.delete;
v_user_status_new.delete;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error' ||sqlerrm);
DBMS_OUTPUT.PUT_LINE(o_Error_Text);
v_sql_err :=SQLERRM;
ROLLBACK;
pkg_champ_message_log.champ_message_log ('PKG_MIGRATE_V1_NESTED_MEMBER.p_update_member_status', tname, null,'Nested', v_sql_err,'Error',o_Error_Text,O_STATUS);
END;Now lets talk how can i keep this merge statemnet as the part of the loop. It seems your mind is made up.
Unfortunately, what you're asking makes no sense at all. You can't "loop through a merge statement".
If you don't want to use merge for the entire table at once, the only thing you can do is to break up the table in your USING clause by some sort of range (maybe an account number or whatever). You could then run your code for each range (or even run them in parallel).
The only other option is to not use MERGE at all and duplicate the logic of it within your loop (which is what I said in my first response). -
Looping thru enumeration objects
How to loop thru the enumeration objects?? Thanks.
If you are using JAVA 5.0 enum, here is an example:
public class Example
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args)
for (Season s : Season.values())
System.out.println(s);
} -
Looping through SQL statements in shell script
Hello members,
I'm working on the Solaris environment and the DB i'm using is Oracle 10g. Skeleton of what I'm attempting;
Write a ksh script to perform the following. I have no idea how to include my sql query within a shell script and loop through the statements. Have therefore given a jist of what I'm attempting, below.
1. Copy file to be processed (one file at a time, from a list of 10 files in the folder ).
for i in *
do
cp $i /home/temp[/CODE]2 . Create a snapshot(n) table : Initialize n = 1 -- -- To create my snapshot table and inserts records in SQL
create table test insert account_no, balance from records_all;3. Checking if the table has been created successfully:
select count(*) from snapshot1 -- query out the number of records in the table -- always fixed, say at 400000
if( select count(*) from snapshot(n) = 400000 )
echo " table creation successful.. proceed to the next step "
else
echo " problem creating table, exiting the script .. " 4. If table creation is successful,
echo " select max(value) from results_all " -- printing the max value to console
5. Process my files using the following jobs:
./runscript.ksh - READ -i $m ( m - initial value 001 )
./runscript.ksh - WRITE -i $m ( m - initial value 001 -- same as READ process_id )
-- increment m by 1
6. Wait for success log
tail -f log($m)* | -egrep "^SUCCESS"7. looping to step1 to :
Copy file 2 to temp folder;
create snapshot(n+1) table
Exit when all the files have been copied for processing.
done -- End of Step 1
Pointers on getting me moving will be very valuable.
thanks,
KrisHi,
Are you inserting the data from file or from some table.
If it is from file, I suggest sql loader would be better, I suppose.
If it is from table, then something like this
for i in *
do
sqlplus username/password@db_name<<EOF
create table test select * account_no, balance from records_all;
EOF
exit
doneAnurag -
How to convert simple SQL Select statements into Stored Procedures?
Hi,
How can I convert following SELECT statement into a Stored Procedure?
SELECT a.empno, b.deptno
FROM emp a, dept b
WHERE a.deptno=b.deptno;
Thanking in advance.
Wajidstored procedure is nothing but a named PL/SQL block
so you can do it like this see below example
SQL> create or replace procedure emp_details is
2 cursor c1 is SELECT a.empno, b.deptno
3 FROM scott.emp a, scott.dept b
4 WHERE a.deptno=b.deptno;
5 begin for c2 in c1
6 LOOP
7 dbms_output.put_line('name is '||c2.empno);
8 dbms_output.put_line('deptno is ' ||c2.deptno);
9 END LOOP;
10 END;
11 /
Procedure created.and to call it use like below
SQL> begin
2 emp_details;
3 end;
4 /
PL/SQL procedure successfully completed.
SQL> set serveroutput on;
SQL> /
empno is 7839
deptno is 10
empno is 7698
deptno is 30
empno is 7782
deptno is 10
empno is 7566
deptno is 20
empno is 7654
deptno is 30
empno is 7499
deptno is 30
empno is 7844
deptno is 30
empno is 7900
deptno is 30
empno is 7521
deptno is 30
empno is 7902
deptno is 20
empno is 7369
deptno is 20
empno is 7788
deptno is 20
empno is 7876
deptno is 20
empno is 7934
deptno is 10Edited by: Qwerty on Sep 17, 2009 8:37 PM -
How do I use SQL statements to perform calculations with form fields????
Please help!!! I don't know how to use a SQL statement within my APEX form......
My form is below. The user will enter the values in the form. Click on Submit. Then we need to run a SQL select statement with those values.
Our form looks like this:
Start_Date ____________
Per_Period ____________
Period ____________
[Submit Button]
The user will enter these 3 values in the form.
This is an example of an user providing the values:
Start_Date 03/14/08_______
Per_Period $200.00________
Period 4____________
[Submit Button]
Then they will click the Submit Button.
The SQL statement (BELOW) returns output based on the users selections:
START_DATE PER_PERIOD PERIOD
14-MAR-2008 00:00 200 Week 1 of 4
21-MAR-2008 00:00 200 Week 2 of 4
28-MAR-2008 00:00 200 Week 3 of 4
04-APR-2008 00:00 200 Week 4 of 4
Total 800
This is the full text of the SQL that makes the output above:
with criteria as (select to_date('03/14/08', 'mm/dd/rr') as start_date,
4 as periods,
'Week' as period,
200 per_period from dual),
periods as (select 'Week' period, 7 days, 0 months from dual
union all select 'BiWeek', 14, 0 from dual
union all select 'Month', 0, 1 from dual
union all select 'ByMonth', 0, 2 from dual
union all select 'Quarter', 0, 3 from dual
union all select 'Year', 0 , 12 from dual
t1 as (
select add_months(start_date,months*(level-1))+days*(level-1) start_date,
per_period,
c.period||' '||level||' of '||c.periods period
from criteria c join periods p on c.period = p.period
connect by level <= periods)
select case grouping(start_date)
when 1 then 'Total'
else to_char(start_date)
end start_date,
sum(per_period) per_period,
period
from t1
group by rollup ((start_date, period))
THANKS VERY MUCH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!You're just doing a parameterized report, where the input fields are your parameters.
Check out the Advanced Tutorial titled Parameterized Report here:
http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10497/rprt_query.htm#BGBEEBJA
Good luck,
Stew -
HOW TO: Post a SQL statement tuning request - template posting
This post is not a question, but similar to Rob van Wijk's "When your query takes too long ..." post should help to improve the quality of the requests for SQL statement tuning here on OTN.
On the OTN forum very often tuning requests about single SQL statements are posted, but the information provided is rather limited, and therefore it's not that simple to provide a meaningful advice. Instead of writing the same requests for additional information over and over again I thought I put together a post that describes how a "useful" post for such a request should look like and what information it should cover.
I've also prepared very detailed step-by-step instructions how to obtain that information on my blog, which can be used to easily gather the required information. It also covers again the details how to post the information properly here, in particular how to use the \ tag to preserve formatting and get a fixed font output:
http://oracle-randolf.blogspot.com/2009/02/basic-sql-statement-performance.html
So again: This post here describes how a "useful" post should look like and what information it ideally covers. The blog post explains in detail how to obtain that information.
In the future, rather than requesting the same additional information and explaining how to obtain it, I'll simply refer to this HOW TO post and the corresponding blog post which describes in detail how to get that information.
*Very important:*
Use the \ tag to enclose any output that should have its formatting preserved as shown below.
So if you want to use fixed font formatting that preserves the spaces etc., do the following:
\ This preserves formatting
\And it will look like this:
This preserves formatting
. . .Your post should cover the following information:
1. The SQL and a short description of its purpose
2. The version of your database with 4-digits (e.g. 10.2.0.4)
3. Optimizer related parameters
4. The TIMING and AUTOTRACE output
5. The EXPLAIN PLAN output
6. The TKPROF output snippet that corresponds to your statement
7. If you're on 10g or later, the DBMS_XPLAN.DISPLAY_CURSOR output
The above mentioned blog post describes in detail how to obtain that information.
Your post should have a meaningful subject, e.g. "SQL statement tuning request", and the message body should look similar to the following:
*-- Start of template body --*
The following SQL statement has been identified to perform poorly. It currently takes up to 10 seconds to execute, but it's supposed to take a second at most.
This is the statement:
select
from
t_demo
where
type = 'VIEW'
order by
id;It should return data from a table in a specific order.
The version of the database is 11.1.0.7.
These are the parameters relevant to the optimizer:
SQL>
SQL> show parameter optimizer
NAME TYPE VALUE
optimizer_capture_sql_plan_baselines boolean FALSE
optimizer_dynamic_sampling integer 2
optimizer_features_enable string 11.1.0.7
optimizer_index_caching integer 0
optimizer_index_cost_adj integer 100
optimizer_mode string ALL_ROWS
optimizer_secure_view_merging boolean TRUE
optimizer_use_invisible_indexes boolean FALSE
optimizer_use_pending_statistics boolean FALSE
optimizer_use_sql_plan_baselines boolean TRUE
SQL>
SQL> show parameter db_file_multi
NAME TYPE VALUE
db_file_multiblock_read_count integer 8
SQL>
SQL> show parameter db_block_size
NAME TYPE VALUE
db_block_size integer 8192
SQL>
SQL> show parameter cursor_sharing
NAME TYPE VALUE
cursor_sharing string EXACT
SQL>
SQL> column sname format a20
SQL> column pname format a20
SQL> column pval2 format a20
SQL>
SQL> select
2 sname
3 , pname
4 , pval1
5 , pval2
6 from
7 sys.aux_stats$;
SNAME PNAME PVAL1 PVAL2
SYSSTATS_INFO STATUS COMPLETED
SYSSTATS_INFO DSTART 01-30-2009 16:25
SYSSTATS_INFO DSTOP 01-30-2009 16:25
SYSSTATS_INFO FLAGS 0
SYSSTATS_MAIN CPUSPEEDNW 494,397
SYSSTATS_MAIN IOSEEKTIM 10
SYSSTATS_MAIN IOTFRSPEED 4096
SYSSTATS_MAIN SREADTIM
SYSSTATS_MAIN MREADTIM
SYSSTATS_MAIN CPUSPEED
SYSSTATS_MAIN MBRC
SYSSTATS_MAIN MAXTHR
SYSSTATS_MAIN SLAVETHR
13 rows selected.Here is the output of EXPLAIN PLAN:
SQL> explain plan for
2 -- put your statement here
3 select
4 *
5 from
6 t_demo
7 where
8 type = 'VIEW'
9 order by
10 id;
Explained.
Elapsed: 00:00:00.01
SQL>
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 1390505571
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 60 | 0 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 60 | 0 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | | 0 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
14 rows selected.Here is the output of SQL*Plus AUTOTRACE including the TIMING information:
SQL> rem Set the ARRAYSIZE according to your application
SQL> set autotrace traceonly arraysize 100
SQL> select
2 *
3 from
4 t_demo
5 where
6 type = 'VIEW'
7 order by
8 id;
149938 rows selected.
Elapsed: 00:00:02.21
Execution Plan
Plan hash value: 1390505571
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 60 | 0 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 60 | 0 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | | 0 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
Statistics
0 recursive calls
0 db block gets
149101 consistent gets
800 physical reads
196 redo size
1077830 bytes sent via SQL*Net to client
16905 bytes received via SQL*Net from client
1501 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
149938 rows processed
SQL>
SQL> disconnect
Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing optionsThe TKPROF output for this statement looks like the following:
TKPROF: Release 11.1.0.7.0 - Production on Mo Feb 23 10:23:08 2009
Copyright (c) 1982, 2007, Oracle. All rights reserved.
Trace file: orcl11_ora_3376_mytrace1.trc
Sort options: default
count = number of times OCI procedure was executed
cpu = cpu time in seconds executing
elapsed = elapsed time in seconds executing
disk = number of physical reads of buffers from disk
query = number of buffers gotten for consistent read
current = number of buffers gotten in current mode (usually for update)
rows = number of rows processed by the fetch or execute call
select
from
t_demo
where
type = 'VIEW'
order by
id
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1501 0.53 1.36 800 149101 0 149938
total 1503 0.53 1.36 800 149101 0 149938
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 88
Rows Row Source Operation
149938 TABLE ACCESS BY INDEX ROWID T_DEMO (cr=149101 pr=800 pw=0 time=60042 us cost=0 size=60 card=1)
149938 INDEX RANGE SCAN IDX_DEMO (cr=1881 pr=1 pw=0 time=0 us cost=0 size=0 card=1)(object id 74895)
Elapsed times include waiting on following events:
Event waited on Times Max. Wait Total Waited
---------------------------------------- Waited ---------- ------------
SQL*Net message to client 1501 0.00 0.00
db file sequential read 800 0.05 0.80
SQL*Net message from client 1501 0.00 0.69
********************************************************************************The DBMS_XPLAN.DISPLAY_CURSOR output:
SQL> -- put your statement here
SQL> -- use the GATHER_PLAN_STATISTICS hint
SQL> -- if you're not using STATISTICS_LEVEL = ALL
SQL> select /*+ gather_plan_statistics */
2 *
3 from
4 t_demo
5 where
6 type = 'VIEW'
7 order by
8 id;
149938 rows selected.
Elapsed: 00:00:02.21
SQL>
SQL> select * from table(dbms_xplan.display_cursor(null, null, 'ALLSTATS LAST'));
PLAN_TABLE_OUTPUT
SQL_ID d4k5acu783vu8, child number 0
select /*+ gather_plan_statistics */ * from t_demo
where type = 'VIEW' order by id
Plan hash value: 1390505571
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers | Reads |
| 0 | SELECT STATEMENT | | 1 | | 149K|00:00:00.02 | 149K| 1183 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 1 | 149K|00:00:00.02 | 149K| 1183 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | 1 | 149K|00:00:00.02 | 1880 | 383 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
20 rows selected.I'm looking forward for suggestions how to improve the performance of this statement.
*-- End of template body --*
I'm sure that if you follow these instructions and obtain the information described, post them using a proper formatting (don't forget about the \ tag) you'll receive meaningful advice very soon.
So, just to make sure you didn't miss this point:Use proper formatting!
If you think I missed something important in this sample post let me know so that I can improve it.
Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/Alex Nuijten wrote:
...you missed the proper formatting of the Autotrace section ;-)Alex,
can't reproduce, does it still look unformatted? Or are you simply kidding? :-)
Randolf
PS: Just noticed that it actually sometimes doesn't show the proper formatting although the code tags are there. Changing to the \ tag helped in this case, but it seems to be odd.
Edited by: Randolf Geist on Feb 23, 2009 11:28 AM
Odd behaviour of forum software -
Multiple Select List looping thru PL/SQL function body returning SQL query
Hi,
I have a Multiple Select List. I want to loop through the values from the Select List and process them in a PL/SQL function body returning a SQL query. Currently, my code only returns the SQL SELECT results of one item in the select list. How do I change my code to make it return the results of all of the items in the select list? (I tested it and it is definitely picking up all the values in the select list).
<b>
DECLARE
selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
s VARCHAR2(20);
q varchar2(32767);
BEGIN
selected_items := HTMLDB_UTIL.STRING_TO_TABLE(:P50_SELECTED_INSTRUMENTS);
-- htp.p('COUNT: '||selected_items.count);
FOR i in 1..selected_items.count LOOP
s := TO_CHAR(selected_items(i));
-- htp.p('First: '||s);
-- htp.p('Second: '||:s);
-- htp.p('Third: '||TO_CHAR(selected_items(i)));
q:= 'SELECT '||
'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
'sum(orig_intrl) orig_intrl, '||
'sum(orig_extrl) orig_extrl, '||
'sum(recv_intrl) recv_intrl, '||
'sum(recv_extrl) recv_extrl '||
'FROM line_usage_sum_view '||
'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''' || s ||'%'' '||
--'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
'AND '||
:SORTFIELD||' BETWEEN '||
'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
-- htp.p('SQL query: '||q);
RETURN q;
END LOOP;
END;</b>
Thank you,
LauraLaura,
First, I would be careful of introducing SQL Injection possibilities. Any time I see
'Select ... ' || :P123_FOO || ' ... '
I worry about sql injection. In your case you are converting :P50_SELECTED_INSTRUMENTS into selected_items and then selected_items into s. So when I see
'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''' || s ||'%'' '||
I think, "I could use sql Injection and hack this."
So, I would do some validation on :P50_SELECTED_INSTRUMENTS or some other method to avoid this.
I'm not certain I understand your query. Do you really intend to allow the user to select the beginning of a string and then find all rows that start with that string? Or, do you just want to let them find when it matches the string. This is one way if you want to do matching:
DECLARE
selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
s VARCHAR2(32767);
q varchar2(32767);
BEGIN
-- Change the : separate string to be comma separated with quoted strings
s := '''' || replace(:P50_SELECTED_INSTRUMENTS, ',', ''',''')|| '''' ;
-- htp.p('COUNT: '||selected_items.count);
q:= 'SELECT '||
'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
'sum(orig_intrl) orig_intrl, '||
'sum(orig_extrl) orig_extrl, '||
'sum(recv_intrl) recv_intrl, '||
'sum(recv_extrl) recv_extrl '||
'FROM line_usage_sum_view '||
'WHERE TO_CHAR(orig_geo_loc_sys) in (' || s ||' ) '||
--'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
'AND '||
:SORTFIELD||' BETWEEN '||
'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
-- htp.p('SQL query: '||q);
RETURN q;
END;
If you want to do something more like you originally stated, try this:
DECLARE
selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
s VARCHAR2(20);
q varchar2(32767);
BEGIN
selected_items := HTMLDB_UTIL.STRING_TO_TABLE(:P50_SELECTED_INSTRUMENTS);
-- htp.p('COUNT: '||selected_items.count);
q:= 'SELECT '||
'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
'sum(orig_intrl) orig_intrl, '||
'sum(orig_extrl) orig_extrl, '||
'sum(recv_intrl) recv_intrl, '||
'sum(recv_extrl) recv_extrl '||
'FROM line_usage_sum_view '||
'WHERE 1=1 ';
FOR i in 1..selected_items.count LOOP
s := TO_CHAR(selected_items(i));
q := q || ' and TO_CHAR(orig_geo_loc_sys) LIKE '''|| s ||'%'' ' ;
END LOOP;
q := q || ||'%'' '||
--'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
'AND '||
:SORTFIELD||' BETWEEN '||
'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
-- htp.p('SQL query: '||q);
RETURN q;
END;
Hope this helps...
Anton -
How to change Bulk Insert statement from MS SQL to Oracle
Hi All,
Good day, I would like to bulk insert the content of a file into Oracle db. May I know how to change the below MS SQL syntax to Oracle syntax?
Statement statement = objConnection.createStatement();
statement.execute("BULK INSERT [TBL_MERCHANT] FROM '" MERCHANT_FILE_DIR "' WITH ( FIELDTERMINATOR = '~~', ROWTERMINATOR = '##' )");
Thanks in advance.
cs.Oracle SQL Loader utility allows you to insert data from flat file to database tables.
Go to SQL Loader links on following url to learn more on this utility
http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/server.920/a96652/toc.htm
Chandar -
How to loop through Multiple Excel sheets and load them into a SQL Table?
Hi ,
I am having 1 excel sheet with 3 worksheet.
I have configured using For each loop container and ADO.net rowset enumerator.
Every thing is fine, but after running my package I am getting below error
[Excel Source [1]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009. There may
be error messages posted before this with more information on why the AcquireConnection method call failed.
Warning: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (5) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified
in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
[Connection manager "Excel Connection Manager"] Error: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "Microsoft Access Database Engine" Hresult: 0x80004005 Description: "The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by
another user, or you need permission to view and write its data.".
Pleas suggest me the correct way of solving above issues.
Thanks in advance :)
regards,
Vipin jha
Thankx & regards, Vipin jha MCPHi ,
Please refer the below link for Looping multiple worksheet in a single SQL Table.
http://www.singhvikash.in/2012/11/ssis-how-to-loop-through-multiple-excel.html
Note:-If you using excel 2010 then you have to use EXCEL 12.0 .
Above link explaining step by step of Looping multiple worksheet in a single SQL Table.
regards,
Vipin jha
Thankx & regards, Vipin jha MCP -
How to run a sql statement with bind variable in a test environment
Hello,
I have a sql statement in prod that I like to run in test. I got the sql statement from statspack, but the statement has bind variables. How do I get this statement to run in test? Thank you.Hi,
If you have the SQL statement and all the referenced objects are available in your test env then what is the problem to run it?
If I am not wront to get your reqmnt...
i.e
SQL> select * from emp
where emp_no = &empno
and dept_code = &deptcode;
Thanks
Maybe you are looking for
-
Cisco Wireless AP configuration as DHCP
I have 10 Cisco 1242 wireless Ap in my Office. 04 of them will be relocated in a different place where we dont have any DHCP server. I would like to configure those AP's as DHCP provider for their associated clients. Is it possible I know but I dont
-
I upgraded to 8.0.2 today and now I can't insert tables. I reverted to version 8 and tested, then 8.0.1, and then to 8.0.2. Still broken. The error says: "While executing objectTag, the following JavaScript error(s) occurred: At line 26 of file "Maci
-
Hi, Please, I'm using ojxqi to execute queries in XML files. I have some problems: How can I execute queries in a XML file with Namespaces? e.g. (example.xml) <videolib> <dc:title>Something</dc:title> <dc:creator>Alex</dc:creator> <cit
-
Purchase Organisation not copying to PR
I am creating a PR thru MRP run (MD02) and PR is getting generated. My next step is to execute Auto PO creation using ME59N, but it was faling and I found that my earleir PR doesnot have Pur Org data in its line item. Eventhough I am having Purchase
-
Problem with old VoIP between modem and Time Capsule
Hi, I hope someone can help me with this.. For a job I used to have, I had a D-Link DVG-5102S VoIP adapter/router that I had to have between my Motorola DSL modem and my Time Capsule WiFi. The service that the D-Link was used for has been shut off fo