Autonomous Transactions
Autonomous Transactions
Autonomous Transactions
Answer Question
Showing Answers 1 - 2 of 2 Answers
VASU
Answered On : Oct 20th, 2012
BY USING AUTONOMOUS TRANSACTION
WE GET THE FOLLOWING ADVANTAGES
WE PROCEDURE HAVING TRANSACTIONS STATEMENTS WE CALL PROCEDURE AUTOMATICALLY EFFECT
THE ABOVE TRANSACTIONS ALSO TO OVERCOME THAT PROBLEM WE HAVE TO USE AUTONOMOUS
TRANSACTION..
Answer Question
Keyword Pragma signifies that the statement is a pragma (compiler directive). Pragmas are processed at
compile time, not at run time.
Oracle collections
What are the types of collection in PL/SQL? What is the advantage of nested tables?
Asked by: sidd_130 | Member Since Oct-2012 | Asked on: Oct 6th, 2012
View all questions by sidd_130
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Varrays,nested tables,index by tables are oracle collection.Index by tables also known as associative
array similar to hashtables in java. Varrays are like arrays in java static in nature need to define
maximum size at time of declaration.Nested tables are like nested class in java holding a table as a
column of a table.
The PLSQL Engine first makes a copy of the record and then during program executing makes a
changes to that copy.
Regards
Jegadeesan
Answer Question
NOCOPY will instruct Oracle to pass the argument as fast as possible. This can significantly enhance
performance when passing a large value.
Answer Question
Login to rate this answer.
vmahawar
Answered On : Apr 18th, 2007
NOCOPY Parameter in Oracle Procedure is used to pass arguments to the any procedure and function as
Reference to improve the performance of the code.
This is done in case the arguments like records, pl/sql tables are passed to the called procedures.
Answer Question
If one wants to send the IN paramter too as pass by reference he could add NOCOPY
parameter....
disadvantage is when there is a change happened to the Reffered value and a rollback occurs in the
procedure the change of value would be retained.... it could not be rolled back....
When a parameter is passed as an IN variable, it is passed by reference. Since it will not change, PL/SQL
uses the passed variable in the procedure/function. When variables are passed in OUT or INOUT mode,
a new variable is define, and the value is copied to the passed variable when the procedure ends. If the
variable is a large structure such as a PL/SQL table or an array, the application could see a performance
degradation cause by copying this structure.
The NOCOPY clause tells to PL/SQL engine to pass the variable by reference, thus avoiding the cost of
copying the variable at the end of the procedure. The PL/SQL engine has requirements that must be met
before passing the variable by reference and if those requirements are not met, the NOCOPY clause will
simply be ignored by the PL/SQL engine.
Answer Question
1 User has rated as useful.
2) OUT parameter mode -This mode is used to return a value to the main block. The value of OUT
parameter can change anywhere in the program.
3) IN OUT parameter mode-This mode is used to pass values to the calling module and return a value to
the main block. The value of IN OUT parameter can change anywhere in the program.
In Call By value, the copy of actual parameter is passed to the formal parameter, So any changes to the
formal parameter doesn't affect the actual parameter.
In Call By reference, the address of actual parameter is passed to the formal parameter, so any changes
to the formal parameter will change the actual parameter also, because both of them are pointing to the
same memory location. Here no copying is required.
The IN parameter is passes by reference, so we can't change the value of IN parameter inside the
module, It acts as a constant, But the OUT and IN OUT parameters are passed by value, we can change
the values of OUT & IN OUT parameters if you use the hint NOCOPY with OUT Parameter and IN OUT
Parameter then ::: call by reference
Answer Question
2 Users have rated as useful.
sipsin: Actually the reverse is true. Usually the IN parameter is passed by reference and the OUT/IN OUT
parameters are passed by value.
Answer Question
Actually it is more useful when we are passing a large record or a large table.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
More over Explicit Cursors were used to retrieve values from two or more rows.
Answer Question
1 User has rated as useful.
implicit cursors are definfined by the oracle server whenever the operations are on single row where as
for operations on mutiple rows the programmer declare cursors explisitly.
Answer Question
Every Select statement is an implicit cursor. As others have said, you do not need to worry about how the
rows are managed. In explicit cursors you can do further work while looping. There is a better chance
that the Explicit cursor statement is cached to a better extent that the implicit cursor statement, therefore
the more times you run it (the explicit cursor) the better the performance gets.
Answer Question
Implicit cursors are declared by PL/SQL implicitly for all DML and PL/SQL SELECT
statements, including queries that return only one row. Explicit cursors for queries that return
more than one row, explicit cursors are declared and named by the programmer and manipulated
through specific statements in the block’s executable actions.
Answer Question
1 User has rated as useful.
PL/SQL uses two types of cursors: implicit and explicit. PL/SQL declares a cursor implicitly for all SQL
data manipulation statements, including queries that return only one row. However, for queries that
return more than one row, you must declare an explicit cursor, use a cursor FOR loop, or use
theBULK COLLECT clause.
Answer Question
Explicit cursors are user-defined cursors.If we use explicit cursor user need to open,fetch and close the
cursor by using explicit cursor we can return more than one records..
The main difference between Implicit and Explicit cursors is by using implicit we can execute only record
where as Explicit returns more than one records. implicit cursor is do open the cursor and fetching data
and closing cursor where as Explicit is User defined user needs open cursor and fetching data and close
the cursor.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
A function is a store procedure indeed, and you can use autonomous transactions to do some DML
Answer Question
First
Previous
Next
Last
Answer Question
1. Function is mainly used in the case where it must return a value. Where as a procedure may or may
not return a value or may return more than one value using the OUT parameter.
Â
2. Function can be called from SQL statements where as procedure can not be called from the sql
statements
3. Functions are normally used for computations where as procedures are normally used for executing
business logic.
4. You can have DML (insert,update, delete) statements in a function. But, you cannot call such a function
in a SQL query.
5. Function returns 1 value only. Procedure can return multiple values (max 1024).
6.Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that
uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation
but runtime throws error Function wont support deferred name resolution.
7.Stored procedure returns always integer value by default zero. where as function return type could be
scalar or table or table values
Taral Desai
functions can be useed in select or update or delete statement while procedure can't.
Answer Question
Login to rate this answer.
Sunil Yadav
A Function can be used in the Sql Queries while a procedure can not be used in sql queries .that cause a
major difference b/w function and procedures .
Answer Question
promila
We can use DDL in Procedure using Execute Immediate statement while tht is not possible in functions
Answer Question
marisamy
Haripriya
Answered On : Dec 23rd, 2005
prem123
procedure can call in another project but function work in same project .
Answer Question
aseemnaithani
We can't have any DDL,DML and TLC command inside a function, if that function is called from
aquery.But if the function is not called from query then we can have all transactional statement(DDL,DML
and TLC ) inside a function.
Answer Question
jaidev_ncc
function can return a single values at maximum, where as in case if procedure returns one or more than
one value and might not return a even a single value........
Answer Question
prafull.vn
Answered On : Mar 19th, 2006
Deepika S Verma
Vikas Rathore
Krishna Gupta
1. A function return single value through return statement but procedure can return one or more than
one values through parameter.
2. function use through select statement while procedure can not.
Answer Question
Rajasekar
Functions are basically pre-compiled, but procedures are not. Thats why we are able to call functions
from select statement but not procedure. In that case, functions are fater than proceduers. Please correct
me if i am wrong.
Answer Question
kiran
A Function can return a single value using return statement, whereas a Procedure cannot return using
return statement but can return using parameters, i.e., a procedure can return one or more values.A
Function can be called inside the select statement, whereas the Procedures cannot called inside the select
statement,procedures are standalone.
Answer Question
A can not be executed or exist as a standalone entity while PROCEDURE hasn't got any of such
limitations. A PROCEDURE can contian one or more FUNCTION.
Answer Question
gautam
Function can create and return a table where as procedure can not return a table
Answer Question
Rajesh
function and procedure both return value But fuction return onlyfor caller. PROCEDURE returns for all of
them.
Answer Question
Sujaatha
Both are nothing but set of statement which will perform some operations... More over both are same...in
C we call it as functions.. in Pascal & COBOL..we call it as procedures..But the d/f b/w this two is function
will return a value to call function...but procedure wont return any value to call function....
Answer Question
think
both are precompiled but act differently like for exe: functions can be called at any point of queries but u
cant do the same with procedure and so on
Answer Question
abhi
Fuctions are used to return a value whileprocedures are used to performa task.
Functions can have out parameter which can take the return type
Answer Question
prabhat saxena
narendra
Srinivasa Reddy
sureshbala
1) A function should return a value as default. whereas a procedure may or may not return a value in
demand.
2) Functions can be integrated in a SQL select statement. But it cannot be applied to procedures.
3) A function can becalled inside a procedure whereas the vice versa is not applicable.
Answer Question
madhu
Vijay Jadhav
malik.aman
Function can return at most one value at a time while procedure can return more than one value at a
time You can use function within Sql Statement and you cannot use stored procedure with in Sql
Statement
Answer Question
g_sidhu
Functions:
krishnaindia2007
1. Function is mainly used in the case where it must return a value. Where as a procedure may or may
not return a value or may return more than one value using the OUT parameter.
2. Function can be called from SQL statements where as procedure can not be called from the sql
statements
3. Functions are normally used for computations where as procedures are normally used for executing
business logic.
4. You can have DML (insert,update, delete) statements in a function. But, you cannot call such a
function in a SQL query.
5.Function returns 1 value only. Procedure can return multiple values (max 1024).
6.Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that
uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during
creation but runtime throws error Function wont support deferred name resolution.
7.Stored procedure returns always integer value by default zero. where as function return type could be
scalar or table or table values
9.A procedure may modify an object where a function can only return a value The RETURN statement
immediately completes the execution of a subprogram and returns control to the caller.
Answer Question
vinothkumar.g
MANIKANDAN
2. Procedure may return one or more values(max 1024) through parameter but function must return only
one values through return statements.
3. Function can use DDL and DML SQL statements, But procedure used for calculation and updation
operation.
Answer Question
2. A function can be called inside a procedure. Reverse is not possible unless you use Execute Immediate
to generate dynamic code which is executed during runtime.
4. If you want to do overloading of functions or procedures, you should seal them in a package. If not,
you cannot overload functions or procedures
5. Though functions allow insert statements in it, it throws error when you use the function in select
statement. Procedure goes good with Insert statements.
Answer Question
jagat
[1] function return value whereas procedure can return one , more than one or no value
Also You can use DDL statements in functions & procedure by using execute_immediate package in latest
version and for parse_sql package in old oracle version. So regarding using of DDL or DML statements in
function or procedure , there is no difference in that context
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
When you drop a type body, the object type specification still exists, and you can re-create the type
body. Prior to re-creating the body, you can still use the object type, although you cannot call the
member functions.
Oracle locks
With what ways can we find out instance locks?
Asked by: sidd_130 | Member Since Oct-2012 | Asked on: Oct 6th, 2012
View all questions by sidd_130
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
TRUNCATE
It's a DDL command and delete the complate table data and no rollback possible.It also resets the HIGH
WATERMARK which will imporve subsequent query performance.
DELETE
This is DML statement and require commit to make changes permanant.Can be used to delete selective
rows from table.Does not reset the High Watermark of the table.
Answer Question
1 User has rated as useful.
Nagabhushan S N is right.
Answer Question
TRUNCATE
It is possible to Delete data permanantly from the table without commit.
After deletion don't have rollback option.
DELETE
Require commit to make changes permanantly after delete command.
and also u can select particular row to delete with where conditions.
here after deletion have rollback option
Answer Question
Login to rate this answer.
D.Madhu
Answered On : Jun 29th, 2006
Delete
DML Operation.
No Auto Commit.
Truncate
DDL Operation
Auto Commit
Answer Question
2. Delete command deletes records one by one where as truncte removes all the records at a time.
3. Truncate does not allow conditional remove of records where as delete allows conditional remove of
records
4.Trigger fires on delete statement where as trigger do not fires on truncate statement.
Answer Question
1 User has rated as useful.
1) TRUNCATE fires 2 COMMIT before firing and after deleting the rows. The COMMIT fired before,
commits all the open uncommitted transactions.
2) TRUNCATE does not write into redo/undo logs which makes it faster than DELETE.
Correct me if I am wrong.
Cajie
Answer Question
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Cursor for loop implicitly declares a loop index as %rowtype. It uses result of query to determine
dynamically no of times the loop is to be repeated. It performs open, fectch , close operations implicitly.
Answer Question
1 User has rated as useful.
If we use cursor for loop cursor will open the cursor and fetching data and close the cursor automatically.
Answer Question
Cursor for loop is the one by using this we need not to perform open, close, fetch operations of a cursor..
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Answer Question
Login to rate this answer.
Jose George
Answered On : Oct 16th, 2012
Depending on the situation one can use
external tables
or
UTL_FILE package
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Data auditing , Implementing complex business rules, security are main uses of database triggers.
Answer Question
3 Users have rated as useful.
by using trigger we can do the auditing and perform a operation(modifications) on a tables (using dml
operation)
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
1.in:
in parameter mode is used to pass values to subprogram when invoked.
2.out:
out is used to return values to callers of subprograms
3.in out:
it is used to define in and out
Answer Question
1> IN
2> OUT
3>INOUT.
Cheers,
Bonthu
Answer Question
IN (default): Passes a constant value from the calling environment into the procedure
OUT :Passes a value from the procedure to the calling
environment
IN OUT :Passes a value from the calling environment into the procedure and a
possibly different value from the procedure back to the calling environment
using the same parameter
Answer Question
2 Users have rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
12 triggers max
Answer Question
Till oracle 7.0 only 12 triggers could be associated with a given table, but in higher versions of Oracle
there is no such limitation.
Answer Question
1 User has rated as useful.
Hi,
There is no limit on number of triggers on one table.
you can write as many u want for insert,update or delte by diff names.
Sunil.
Answer Question
1 User has rated as useful.
if table has got n columns. we can create n triggers based on each column.
Answer Question
Higher version of Oracle doesn't have any limitation of the number of trigger. Earlier 12 number of
triggers were fired per table.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,OUT parameter will be useful for returning the value from subprogram, value can be assigned only
once and this variable cannot be assigned to another variable.IN OUT parameter will be used to pass the
value to subprogram and as well as it can be used to return the value to caller of subprogram. It acts as
explicitly declared variable. Therefore it can be assigned value and its value can be assigned to another
variable.So IN OUT will be useful than OUT parameter.
Answer Question
1) IN OUT and OUT selection criteria depends upon the program need.if u want to retain the value that is
being passed then use seperate (IN and OUT)otherwise u can go for IN OUT.2)If nothing is assigned to a
out parameter in a procedure then NULL will be returned for that parameter.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
hai
just use subquery in for clause
ex:
for emprec in (select * from emp)
loop
dbms_output.put_line(emprec.empno);
end loop;
no exit statement needed
implicit open,fetch,close occurs
try this and send me the reply on [email protected]
Answer Question
2 Users have rated as useful.
Well there may be several ways for not to use a cursor. But a good programming practice suggests the
use of cursors as much as possible for performance and efficiency purpose.
Answer Question
insted of using cursor we will use attribute data types %type and %rowtype to load data in pl/sql
Answer Question
You can use bulk binding to avoid cursors. It improves performance by minimizing context switches sql
and pl/sql. When you are hadling large volume of data then better to use bulk binding.
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Clustering is a method of storing tables that are intimately related and often joined together into the
same area on disk. For example, instead of the BOOKSHELF table being in one section of the disk and the
BOOKSHELF_AUTHOR table being somewhere else, their rows could be interleaved together in a single
area, called a cluster. The cluster key is the column or columns by which the tables are usually joined in a
query (for example, Title for the BOOKSHELF and
BOOKSHELF_AUTHOR tables).
Answer Question
1 User has rated as useful.
Cluster are groups of one or more tables physically stores together to share common columns and are
often used together
What is the need of primary key as opposed to using not null and unique ?
we can create a column with' not null+unique' with out using primary key
Asked by: sreeraghava.nara | Member Since Jun-2008 | Asked on: Jun 16th, 2008
View all questions by sreeraghava.nara
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
One simple diff : there can only one primary key per table but not null+unique can be multiple on one
table.
Answer Question
3 Users have rated as useful.
To add cascading is only possible when it follow primary key - foriegn key constraint.
Answer Question
Primary key provides a default index in it. But we don't have this advantages on the column which we
have NOTNULL and Unique Key instead of Primary Key.
Answer Question
If we use null values it will allow duplicate values but it does not allow null values.
If we use unique key it does not allow duplicate value but it allows null values.
The main difference is if we use primary key it does not allow both null and duplicate values.
What are % TYPE and % ROWTYPE ? What are the advantages of using these
over datatypes?
% TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE
provides the record type that represents a entire row of a table or view or columns selected in the
cursor. The advantages are : I. Need not know about variable's data typeii. If the database definition
of a column in a table changes, the data type of a variable changes accordingly.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Advantage is, if one change the type or size of the column in the table, it will be reflected in our program
unit without making any change.
Answer Question
1 User has rated as useful.
%type is used to refer the column's datatype where as %rowtype is used to refer the whole record in a
table.
Answer Question
1 User has rated as useful.
EX:
V_EMPNOEMP.EMPNO%Type;
Where as
Ex:
V_EMP EMP.%ROWTYPE.
Answer Question
1 User has rated as useful.
%ROWTYPE can be used to declare the variable having the same no. of variables inside it (ROWTYPE) as
no. of columns there in the table. In this case columns selected with SELECT statement must match with
variables inside the rowtype variable. If not then induvidually refer these variables inside the ROWTYPE
variables
Answer Question
1 User has rated as useful.
declare
var1 production.invoice.itemno%type;
%Rowtype - With %rowtype attribute we can inherit the datatypes entire variable into a record varible
from another record variable or from all attributes of table into currently declared record variable.
eg.
declare
record1 production.invoice%rowtype;
Advantage is u need not to change the pl/sql code even if table attribute changes.
u need not to remember detail datatypes of table while coding pl/sql
Answer Question
1 User has rated as useful.
%TYPE is used to declare a variable with the same type as that of a database table column.%ROWTYPE
is used to declare a record as same type found in database table.These two provides data independence
and allows you to adopt database changes due to new business requirements.You need not know
datatype and size in advance.
Answer Question
1 User has rated as useful.
The benefit of %TYPE and %ROWTYPE is when u are fetching the data from a table in procedure and
after that data type of column or size is changed then no need to modify the procedure.
Answer Question
- It is good practice to use %TYPE and %ROWTYPE instead of defining varible of simple type. In case of
any change in the data type of columns and no need to make any changes to code.
- %ROWTYPE can be used to fetch complete row instead ofdefining varible for each field to hold the data
while processing.
Answer Question
We Can USE These Data Types in Stored Procedures ,function and Packages as IN Parameter.
Answer Question
if using %type and %rowtype , no need to know the the data type of the table column . and once the
development is finished , the type of column is changed it will not effect the coding.
Answer Question
%type is associated with one column .(if we want to declare entire column then we need to declare
%type).
explian rowid,rownum?what are the psoducolumns we have?
Asked by: Interview Candidate | Asked on: Jul 28th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
ROWID - Hexa decimal number each and every row having unique.Used in searching
ROWNUM - It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are
NEXTVAL,CURRVAL Of sequence are some exampls
[email protected]
Answer Question
3 Users have rated as useful.
psoducolumn in the sence which is not created by the user explicitly but user can use those things
explicityly.
examples
rowid,rowno,currval,nextval,sysdate,uid,level.
RowID: While storing in the database oracle generates one id for each row.
you can call based upon the rowid .ex: select * from emp where rowid=....
RowNo : This no is also generated by oracle itself. but you cant call based upon this one in select clause
Answer Question
Even ROWID is also not permanent for life time.Because If one exports and imports the table data then
ROWID changes.
Answer Question
1 User has rated as useful.
For each row returned by the query a Rownum, pseudocolumn is returned in which order oracle selects
the rows from the table. Using rownum one can even limit the number of rows selected from the table.
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can
select from pseudocolumns, but you cannot insert, update, or delete their values. This section
describes these pseudocolumns:
- CURRVAL and NEXTVAL
- LEVEL
- ROWID
- ROWNUM
Answer Question
3 Users have rated as useful.
Row NUM: A sequence number used to retrieve rows from the table.
Some other Pseudo columns are - Level, Rowscn, UID, User, Sysdate.
Answer Question
If using ORDER BY with ROWNUM then the rows will be reordered by the ORDER BY clause, means the
sequence of rows will be different. it is better to use ROW_NUMBER() analytic unction.
Example:
SELECT * FROM emp WHERE ROWNUM < 11 ORDER BY ename;
Fix:
SELECT * FROM (SELECT * FROM emp ORDER BY empno) WHERE ROWNUM < 11;
Answer Question
Here I am providing all the psudo columns of Oracle ROWNUM, ROWID,NEXTVAL, CURRVAL, SYSDATE,
USER, LEVEL
Answer Question
rownum is also octal decimal number but it is for only specific time span it will arise after completed a
task.
Transaction management in triggers
Can we give COMMIT or ROLLBACK within a trigger?
Asked by: sidd_130 | Member Since Oct-2012 | Asked on: Oct 6th, 2012
View all questions by sidd_130
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
no triggers cannot use COMMIT and ROLLBACK . And the procedures and functions called by the triggers
also cannot use the COMMIT and ROLLBACK.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three
table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of
rows in each table involved in the join. SO select * from a,b will result in 3x3= 9 rows
Finding object dependencies
How can we find out the dependencies on a table?
Asked by: sidd_130 | Member Since Oct-2012 | Asked on: Oct 6th, 2012
View all questions by sidd_130
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
check the table dba_dependencies and see what other tables are affected.
What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database trigger.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Raise_application_error is used to create your own error messages which can be more descriptive than
named exceptions.
Syntax is:-
Raise_application_error (error_number,error_messages);
where error_number is between -20000 to -20999..
Answer Question
3 Users have rated as useful.
i know that the error no in raise_application_error are non standard but tell me on what basis we are
giving those numbers? is that simply a number or it some implicit meaning ?
Answer Question
Previous
Next
Last
Return back to PL/SQL
Answer Question
Note: Dynamic Cursors are implemented using Oracle built in package DBMS_SQL.
Implicit Cursors:
----------------
Any SQL statement that is executed directly or in an PL/SQL block i.e. execution section or in exception
section, during which it is associated with a work area in memory of oracle (SGA). This is done using
implicit cursor by Oracle.
Explicit Cursors:
-----------------
They are the SELECT statement that is declared explicitly in the declaration section of current block or in
a package
specification.
Further we can use open, fetch and close in execution section or exception section of the block or
program to utilize declared cursor.
To use an explicit cursor we need to declare it in
declaration section of block or package specification.
CURSOR emp_cur IS
SELECT emp_id
FROM emp;
Hope so, above paragraphs explain cursors very well and in details.
Answer Question
A cursor is a private sql area used to stored intermediate data from the sql statements.whenever an sql
statement is fired an cursor get open indirectly which is called as implicit cursor and whenever an user
want to process data based on some sql statements result he has to explicitly define a cursor known as
explicit cursor, A simple cursor is where no parameters are used where as a parametrized cursor is a
cursor where the query result are based explicitly on the parameters passed to the cursor
Code
1. DECLARE
2. CURSOR C1(ENO NUMBER) IS
3. SELECT * FROM EMP
4. WHERE EMPNO=ENO;
5. BEGIN
6.
7. FOR I IN C1(&ENO) LOOP
8. DBMS_OUTPUT.PUT_LINE(ENAME);
9. END LOOP;
10. END;
11.
12.
13.
Answer Question
Simple Cursor - A cursor having a simple or a complex SQL query and which will have conditions based
on given variables or hard-coded.
Parameterized Cursor - such types of cursors will accept parameters i.e. values of the where clause in the
cursor query will depend on the passed parameters.
Answer Question
Cursors having some private area.which is used for store the data from sql statements.Normal cursors we
don't have use any parameters.but parametrized cursors are used the parameters,which is executed
based upon the parameter.
How do you set table for read only access ?
if i am updating one record in a table at that time no other user can't able insert ,update the record in
same table How is it possible
Asked by: nitin_kumat | Member Since May-2006 | Asked on: Mar 20th, 2007
View all questions by nitin_kumat View all answers by nitin_kumat
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
You can use view for this purpose because you can set view as read only.
Answer Question
any other user or session would be able to do any insert/update to the same table only after you release
the table by commit or rollback.....
Answer Question
1 User has rated as useful.
Read only:
ALTER TABLE SALES READ ONLY;
Back to read/write:
ALTER TABLE SALES READ WRITE;
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Use this
Code
1. WHERE rownum < 11
Answer Question
The problem with the question is it is too vague. How are you ordering the inserts because if the inserts
were done in a batch, all 100 records at once, then all 100 records will be "most recent". You could just
as well randomly pick any 10 records from the 100 inserted records and claim that random selected 10
was the "most recently" inserted records. Equally, rownum is meanless since rownum returns a number
indicating the order in which Oracle selects the row from a table, not the order it was insert. You can not
reliably control the order Oracle stores the rows inserted in a table, even if they seem to be inserted
sequentially. If you inserted the same 100 records again, the 10 "most recent" or the 1st 10 records via
rownum might not be the same as the previous 100 records insert/(10 most recent or 1st 10) records -
even if the data in both cases was the same. Assuming you had inserted the records in such a way that
some column, call it column "ord", contained the ordinal record of inserts such a way that ord = 1 was
the 1st record inserted and ord = 100 was the last record inserted then:
Code
1. SELECT t.*
2. FROM <table name> t
3. WHERE t.ord < 11
4.
5. would give you the 1st 10 inserted records, AND :
6.
7. SELECT t.*
8. FROM <table name> t
9. minus
10. SELECT t.*
11. FROM <table name> t
12. WHERE t.ord < 91
would give the 10 most recently inserted records.
Answer Question
select * from (select * from emp e order by rowid desc) where rownum<=10
Answer Question
The "first 10 records of data", there isnt such a concept. There is no such thing as "first 10 records of
data" or "last 10 records of data" there are just rows.
Records are not returned in order of anything. You would have to SORT the data in order to have a "first"
and "last".
If you want the "first 10 records of data" inserted, you need to have a timestamp or sequence number
assigned to each record as they are inserted, then you will get the "first 10 records of data". It is the
ONLY way.
You MUST have some column that you can order by.
Rowid - wont work. The rowid is not "generated" in as much as "derived", it is the address of the row on
disk.
Rowids are not "sequential" things, they say WHERE a row exists, not when a row was inserted or
anything like that. Since space can and will be reused, rowids can and will be "reused". A rowid implies
NOTHING other than the location of the row physically. It does not imply age, order of insertion, or
anything like that.
Rownum -- doesnt work either, it just doesnt work. Rownum is a psuedo column, its value is assigned as
rows are output.
Reference:
"Fetching last record from a table"
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:912210644860
"Rownum"
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:948366252775
Answer Question
2 Users have rated as useful.
The person asking the question is asking for the the "recent 10 records out of 100 records" out of the
"100 records" ... "inserted" ... "today" ... "I want first 10 records data from 100 records"
TODAY - RECENT ... these are orders of TIME, the TIME at which the record was inserted into the table.
The "recent 10 records"/"first 10 records" are records that have been ordered BY THE TIME INSERTED.
To get the "recent 10 records"/"first 10 records" insert "today", you need a column or columns that have
some order related to the time the record was inserted.
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
No , it is not possible. Truncate is a DDL Command and we can not where clause in Truncate.
Answer Question
2 Users have rated as useful.
You can truncate few rows from a table if the table is partitioned. You can truncate a single partition and
keep remaining.
Answer Question
2 Users have rated as useful.
We cannot
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
yes
Answer Question
Yes we can insert multiple nulls as each nulls have different ROWID
Can we write commit or rollback in trigger ?
Asked by: sachinkshd | Member Since Jul-2012 | Asked on: Jul 17th, 2012
View all questions by sachinkshd
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
No. Triggers run as part of transaction. In Oracle you can create an autonomous transaction inside of a
trigger if you really need one.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The cursor having query will get closed, because once the for update clause is fired it locks all the rows
which is been modified and once it encounters a commit/rollback it automatically comes out of that
session, and will be processing a fresh loop altogether.
Answer Question
Login to rate this answer.
Bhanu
Answered On : Oct 19th, 2005
DDL statements cannot be included in the pl/sql block. Hence giving commit is not allowed.
Answer Question
If the data set is too big commiting with-in the cursor loop might lead to the `Snapshot too old Error`.
Answer Question
after the commit statement, the cursor get closed ...as the result no further rows can be fetched even
though there are rows to be fetched.
Answer Question
DECLARE
CURSOR C IS
SELECT * FROM EMP
WHERE ROWNUM <4;
R C%ROWTYPE;
BEGIN
OPEN C;
LOOP
FETCH C INTO R;
DBMS_OUTPUT.PUT_LINE (R.EMPNO);
EXIT WHEN C%NOTFOUND;
UPDATE EMP
SET SAL = SAL-1;
COMMIT;
END LOOP;
CLOSE C;
END;
Answer Question
Cheers!!
Answer Question
Commit in this context will not do anything except the commiting the changes into database, done using
DML statements. However, if the cursor is created with FOR UPDATE clause, it will raise runtime
exception as commit, in that case, would also release all locks and thus close the cursor implicitly and
user will get ORA-1002 "fetch out of sequence " error as after the loop is executed one time, with the
commit statement, the cursor will be closed and fetch into statement will fail.
Answer Question
1 User has rated as useful.
The log writer makes redo log entries in redo log files after that message comes commit complete.
Also by using commit the changes made by update statement will be seen in database permanently.
Answer Question
The data will be written from redo log buffer into redo log files.
Answer Question
After committing first oracle will commit the transaction into redo log file and then Data file. The data
block will remain into the memory until the logical reads are going on. Oracle use LRU algorithm to
maintain the data block into the memory. Also oracle maintain rollback segment before committing the
data to store original version of data.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
A materialized view is a database object that contains the results of a query. They are local copies of data
located remotely, or are used to create summary tables based on aggregations of a table's data.
Materialized views, which store data based on remote tables are also, know as snapshots.A materialized
view can query tables, views, and other materialized views. Collectively these are called master tables (a
replication term) or detail tables (a data warehouse term).
Answer Question
2 Users have rated as useful.
A materialized view or snapshot contains the results of a query of one or more tables, each of which may
be located on the same or on a remote database. Materialized viwes allows to create replications of
tables of remote data with a read-only privillage on the copy. When a materialized view is created, Oracle
creates one table and index, and in the same schema of the materialized view.
Answer Question
1 User has rated as useful.
A materialized view is like a query with a result that is materialized and stored in a table. When a user
query is found compatible with the query associated with a materialized view, the user query can be
rewritten in terms of the materialized view. This technique improves the execution of the user query,
because most of the query result has been precomputed. The query transformer looks for any
materialized views that are compatible with the user query and selects one or more materialized views to
rewrite the user query. The use of materialized views to rewrite a query is cost-based. That is, the query
is not rewritten if the plan generated without the materialized views has a lower cost than the plan
generated with the materialized views.
Answer Question
Materialized views are schema objects that can be used to summarize, precompute, replicate, and
distribute data. E.g. to construct a data warehouse.
Answer Question
A materialized view have a physical memory where it can store the result of query which are combination
in joining of one or more table and view it retrieve a faster result. when we want to refresh the data
which are coming from diffrent application so it retrive the fast result. its a benefit of materialized view.
Answer Question
Refresh intervals represents, how the frequently the materialized view has to be refreshed. Refresh
modes are
1. Complete
2. Fast
3. Force
4. Uncommit
5. On demand
6. Differed
Answer Question
Materialized views are objects that are used in base table that can be Summarized Group, and
aggregated with the base table.This materialized views are used in data-ware housing and decision
support system.
What steps should a programmer should follow for better tunning of the PL/SQL
blocks?
Difference between procedure and function?
What is the use of ref cursor return type?
Asked by: aseemnaithani | Member Since Feb-2006 | Asked on: Mar 15th, 2006
View all questions by aseemnaithani View all answers by aseemnaithani
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The main difference between procedure and function,function should return a value.procedure need not
Answer Question
1 User has rated as useful.
Ref cursor return type can be used when it's required that a procedure / function need to return set of
records.
Answer Question
Tuning can be taken care by using the Correct Index on the table.We should not use Not equal to,
Distinct on the Indexed columns.
Answer Question
1. Always use the where clause in your select statement to narrow the number of rows
returned.
If we dont use a where clause, the Oracle performs a full table scan on our table and
returns all of the rows.
2. Use EXISTS clause instead of IN clause as it is more efficient than IN and performs
faster.
Ex:
Replace
SELECT * FROM DEPT WHERE DEPTNO IN
(SELECT DEPTNO FROM EMP E)
With
SELECT * FROM DEPT D WHERE EXISTS
(SELECT 1 FROM EMP E WHERE D.DEPTNO = E.DEPTNO)
Note: IN checks all rows. Only use IN if the table in the sub-query is extremely
small.
3. When you have a choice of using the IN or the BETWEEN clauses in your SQL , use
the BETWEEN clause as it is much more efficient than IN.
Depending on the range of numbers in a BETWEEN, the optimizer will choose to do a
full table scan or use the index.
4. Avoid WHERE clauses that are non-sargable. Non-sargable search arguments in the
WHERE clause, such as "IS NULL", "OR", "<>", "!=", "!>", "!<", "NOT", "NOT
EXISTS", "NOT IN", "NOT LIKE", and "LIKE %500" can prevent the query optimizer
from using an index to perform a search. In addition, expressions that include a
function on a column, or expressions that have the same column on both sides of the
operator, are not sargable.
5. Use equijoins. It is better if you use with indexed column joins. For maximum
performance when joining two or more tables, the indexes on the columns to be
joined should have the same data type.
6. Avoid a full-table scan if it is more efficient to get the required rows through an
index. It decides full table scan if it has to read more than 5% of the table data (for
large tables).
7. Avoid using an index that fetches 10,000 rows from the driving table if you could
instead use another index that fetches 100 rows and choose selective indexes.
8. Indexes can't be used when Oracle is forced to perform implicit datatype
conversion.
9. Choose the join order so you will join fewer rows to tables later in the join order.
use smaller table as driving table
have first join discard most rows
10. Set up the driving table to be the one containing the filter condition that eliminates
the highest percentage of the table.
11. In a where clause (or having clause), constants or bind variables should always be
on the right hand side of the operator.
12. Do not use SQL functions in predicate clauses or WHERE clauses or on indexed
columns, (e.g. concatenation, substr, decode, rtrim, ltrim etc.) as this prevents the
use of the index. Use function based indexes where possible
13. If you want the index used, dont perform an operation on the field.
Replace
SELECT * FROM EMPLOYEE WHERE SALARY +1000 = :NEWSALARY
With
SELECT * FROM EMPLOYEE WHERE SALARY = :NEWSALARY 1000
14. All SQL statements will be in mixed lower and lower case. All reserve words will be
capitalized and all user-supplied objects will be lower case. (Standard)
16. Try joins rather than sub-queries which result in implicit joins
Replace
SELECT * FROM A WHERE A.CITY IN (SELECT B.CITY FROM B)
With
SELECT A.* FROM A, B WHERE A.CITY = B.CITY
17. Replace Outer Join with Union if both join columns have a unique index:
Replace
SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE (+)
With
SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE
UNION
SELECT NULL, B.CITY FROM B WHERE NOT EXISTS
(SELECT 'X' FROM A.STATE=B.STATE)
18. Use bind variables in queries passed from the application (PL/SQL) so that the same
query can be reused. This avoids parsing.
19. Use Parallel Query and Parallel DML if your system has more than 1 CPU.
20. Match SQL where possible. Applications should use the same SQL statements
wherever possible to take advantage of Oracle's Shared SQL Area. The SQL must
match exactly to take advantage of this.
21. No matter how many indexes are created, how much optimization is done to queries
or how many caches and buffers are tweaked and tuned if the design of a database
is faulty, the performance of the overall system suffers. A good application starts
with a good design.
SELECT DISTINCT
SELECT UNIQUE
SELECT ....ORDER BY...
SELECT....GROUP BY...
CREATE INDEX
CREATE TABLE.... AS SELECT with primary key specification
Use of INTERSECT, MINUS, and UNION set operators
Unindexed table joins
Some correlated sub-queries
Answer Question
2 Users have rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
You can use the following e.g.1. SELECT * FROM ( SELECT deptno, ename , sal , ROW_NUMBER() OVER
( PARTITION BY deptno ORDER BY sal DESC ) Top3 FROM emp )WHERE Top3 <= 3/2. This will give
distinct values.SELECT * FROM ( SELECT deptno, ename , sal , DENSE_RANK) OVER ( PARTITION BY
deptno ORDER BY sal DESC ) Top3 FROM emp )WHERE Top3 <= 3/
Answer Question
1 User has rated as useful.
Hi...
If u want to find the nth record in salary basis then.. I thnik this will work
select * from(select * from emp order by sal desc) where rownum=
Answer Question
1 User has rated as useful.
select * from ( select rownum r, sal,name from (select * from emp order by sal)) where r=
You need to give all column names in first inline view.
Answer Question
select max(sal) from emp a where &n = (select count(distinct sal) from emp where sal >= a.sal);
Answer Question
If we have a table EMP and having data as, if we want second highest sal i.e 5000 the the query will be:
Code
1. EMPNO ENAME SAL
2. 1 A 5000
3. 2 B 2000
4. 3 C 10000
5.
6. SELECT MIN(SAL) FROM (SELECT * FROM EMP ORDER BY SAL DESC)
7. WHERE ROWNUM <=2
8.
Same as nth highest query we need to put that number instead of 2.
Answer Question
It is better to use analytic functions these days as they are faster and smarter and your managers will
think high of you...
Code
1. Top n-paid IN ALL Depts - changer the orde BY dept AND sal DESC IF ant TO find
out top paid IN each dept:
2. SELECT * FROM ( SELECT deptno, ename, sal
3. , ROW_NUMBER() OVER (ORDER BY sal DESC, ename) AS row_num
4. , RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) rank
5. , DENSE_RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) d_rank
6. FROM emp )
7. --WHERE row_num <= 4
8. /
Answer Question
This is incorrect. It will not return anything. One of the possible answer is
Code
1. SELECT salary FROM (SELECT rownum n, a.salary
2. FROM
3. (SELECT DISTINCT salary FROM person ORDER BY salary ) a)
4. WHERE n = 5 ;
Answer Question
This is what I did. I specified n = 1 which means I want the highest salary. then I put the NULL values
for this record in salary column. The record with NULL value always shows me as the highest salaried
employee which is incorrect.
Answer Question
use
Code
1. NVL(a.sal,0)<= NVL(b.sal,0)
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
When we use a select query in the from clause, it is called as a inline view. It is used to reduce
complexity of using so many join conditions.
What is nested table in Oracle and difference between table and nested table?
Asked by: Vikramsingh | Member Since Oct-2007 | Asked on: Oct 23rd, 2007
View all questions by Vikramsingh
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Answer Question
2 Users have rated as useful.
Login to rate this answer.
Anu Ramakrishnan
Answered On : Nov 27th, 2007
Nested table is the collection object in oracle . It is also stored in database one in a separate file called
store file .This can be used as a column in a table like VARRAY. This is created in a database
usingcreate type command .It is used for storing a single dimensional value like VARRAY. The
difference between VARRAY and nested table is we can have numerous value single table but in case of
VARRAY we can not have more than the defined limit .
Answer Question
In Oracle nested table are considered one-column database tables. Tables which are having one table as
a cell. Nested tables are like one-dimensional arrays stored in a table, but we can model nested table to
hold multi-dimensional arrays.
Answer Question
VARRAYS:
stored with in the table
supports limited rows
DML not allowed
Answer Question
Login to rate this answer.
krishnaindia2007
Answered On : May 6th, 2008
View all answers by krishnaindia2007
A Table is a basic unit of storage in oracle.
A nested table is a collection type. The main advantage of collections is instead of processing data
sequentially, we may process all the date in one step.
- It is a collection of rows stored as a column in a table.
- It is a table withing a table.
- There is no restriction on number of rows in a nested table
- There is no restriction on number of columns in a nested table.
- We can not index nested table.
- The nested table is stored as a seperate table and main table maintains a pointer to the nested table as
reference.
- Nested table stored data in no particular order
- But when you retrieve data into pl/sql variable it assigns serial number starts with 1
- Intially they are dense you may sparse later.
- Nested tables are unbounded. There is no upper limit.
Answer Question
1 User has rated as useful.
VArrays
Bounded
Individual element cannot be deleted.
Stored by Oracle in- line
Do not support indexes.
Not flexible than nested table.
Data is stored as single object in database.
Stored within table.
DML are not allowed
Oracle exception block
In the exception part,what will happen if u dont give (when others) where will it show error compile time
or run time
Asked by: nabiel_pathan | Member Since Feb-2011 | Asked on: Feb 13th, 2012
View all questions by nabiel_pathan
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Run time
Answer Question
If there were other when statements in the exception the code would compile, if an exception occurred
and the other could not handle the error, then the handling of the error would be be moved up the
calling stack until it was either handled or the application terminated because of the un-handled run-time
error.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
No
Answer Question
yes
Answer Question
1 User has rated as useful.
Yes
Answer Question
Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored
procedure/function. The code in this part of the program gets executed like those in the body without
any restriction. You can include any business functionality whenever a condition in main block(body of a
proc/func) fails and requires a follow-thru process to terminate the execution gracefully!
Answer Question
4 Users have rated as useful.
yes we can
Answer Question
COMMIT;
RAISE;
END
Answer Question
Yes
Answer Question
Yes, we can use Commit / Rollback in the Exception part. Declare ---Variable declaration Begin ----
Executable part Exception When others then dbms_output.put_line(sqlerrm); Rollback; END ;
Answer Question
1 User has rated as useful.
Yes We can
Answer Question
Declare
myexception EXCEPTION;
Begin
RAISE myexception;
EXCEPTION
When myexception then
insert into table_name values (......);
COMMIT;
yes we can......
Answer Question
no, we can't use exceptions in ddl statements.normal form sql or sql*plus,without explicitly issuing
commit or rollback statements.
Answer Question
yes.. surely.. you can use any TCL command within the exception block.
Answer Question
Yes. You can very well use COMMIT or ROLLBACK in exception block. But it is not a good idea to use, as
it will commit the previous transactions in the same PLSQL block. Make use of creating SAVEPOINTS and
commiting them when required.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
If select query is retrieving less than 200 records go for implicit cursor.
Code
1.
2. begin
3. for i in (select * from emp)
4. ----------------
5. end
Else use explicit cursor
Code
1. declare
2. cursor c1 is select * from emp_morethan200
3. begin
4. for i in c1 loop
5. ----------------
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Oracle hints are used when there is a need to instruct or guide the Oracle optimizer to make custom
decisions instead of its own decisions which are made based on database statistics.
That means by making use of Hints we are basically giving instruction to the optimizer and telling it which
route it should follow to execute the code and thereby affecting the outcome of Oracle optimizer's
decision.
Jonathan Lewis states that "Hints are interception points in the optimizer code path, and must be
obeyed."
and he further adds that "Hint affects the optimizers route through its code path."
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
basically the %rowtype is used in case of fetching the values of the cursor irrespective of how many
columns in it and also the data types associated with the tables column.for eg.
declare
cursor c_example is select * from emp;
v_emp emp%rowtype;
begin
for v_emp in c_example loop
statements
......
end loop;
end;
the type record is a object oriented concept related to pl/sql tables, tables with datastructure format etc.
create type ty_name is record ( a number,
b varchar2(10));
this type stores data in a record fashion with 2 columns.
Answer Question
1 User has rated as useful.
%rowtype is an attribute to inherit datatypes of attributes of a table into a RECORD variable. Type record
is a keyword to create record type using either explicitly specifying atrributes or by implecitly inheriting
attributes from a table or a existing cursor.
Answer Question
DECLARE
TYPE extra_book_info_t
IS RECORD (
title books.title%TYPE,
is_bestseller BOOLEAN
);
first_book extra_book_info_t;
here, 'title' is the data type defined in books table. We can declare a RECORD based on this type.
Where as %ROWTYPE is a direct link to the data type of the table.columns, EG:
DECLARE
bestseller books%ROWTYPE;
The advantage of TYPE RECORDS is you can pass these to Functions or Procedures which can reduce the
parameter size or a repitative work.
Hope this give a better explanation.
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
using utl_mail
Answer Question
UTL_MAIL: type procedure in UTL_MAIL 1)SEND (send the message without attachment)
Code
1. BEGIN
2. UTL_MAIL.SEND(sender=>'[email protected]',recipients=>'[email protected]
',message =>'HAPPY BIRTHDAY',subject => 'birthday wishes');
3. END
4. 2)SEND_ATTACH_RAW(FOR message WITH binary attachment)
Code
1. BEGIN
2. UTL_MAIL.SEND_ATTACH_RAW(sender=>'[email protected]',recipients=>'karimuthu.bal
[email protected]',message =>'HAPPY BIRTHDAY',subject => 'birthday wishes'
3. mime_type => 'text/html',attachment => get_image('oracle.gif'),att_inline=>true,a
tt_min_type =>'image/gif',att_filename =>'oracle.gif');
4. END
3)SEND_ATTACH_VARCHAR2(for messages with text attachment)
Code
1. UTL_MAIL.SEND_ATTACH_VARCHAR2(sender=>'[email protected]',recipients=>'karimuth
[email protected]',message =>'HAPPY BIRTHDAY',subject => 'birthday wishes'
2. mime_type => 'text/html',attachment => get_file('test.txt'),att_inline=>flase,att
_min_type =>'text/plain',att_filename =>'test.txt');
3. END
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
we can return only one value at a time. if we want more then one value we directly assign that value to
the variable(ii) Types of triggers(*) row level trigger(*) statement level trigger(*) Before Trigger(*) After
Trigger
Answer Question
Answer Question
1)Use Ref cursor to retuen more than one value. 2)Till oracle 8i there are 13 types of Database triggers.
For 3 DML operations (ADD,DEL,MOD) before and after triggers Ex Before delete, After delete, Before
update after update etc that'll make 6 triggers. For each 6 row level and statemnet level that'll make 12
types of triggers. 1 instead of triggers. to manipulate complex views . from 9i onwards new triggers have
been introduced to logon and log off.3) There are 400 new features in oracle 9i . but mostly they are
into DW concepts. and for developers point of view. Merge, Flashback query, New features in DB
triggers, aditional features in Row id etc. Hope this wil helpHarikishan
Answer Question
If you want to return more than 1 value & dont want to use ref curser...try this, 1. Return comma
separated varchar & then use dbms_utility.comma_to_table function to parse them.2. Try returning
variable of type pl/sql table or varray.I have not tried number 2, but should work.
Answer Question
HI Shekhar,
can you please give me some example that how to return multiple values from a function
using a comma separated varchar and parse it. I'm stuck in that situation and found solution using varry
type. If getting the comma separated varchar would be better.
Thanks & regards
Rupak
Answer Question
More than one values can be returned to the calling environment by a function is achieved by declaring
INOUT parameters or OUT parameters in the function .
but it is not good programming practise to force a function to return more than one values...
Answer Question
Can you provide a simple code showing how ref cursor can be used to return more than one values from
the function? It would be very helpful.
Thanks
Answer Question
DECLARE
A1 NUMBER(3) := 10;
B1 NUMBER(3) := 20;
C1 NUMBER(3) := 30;
D1 NUMBER(3) := 40;
BEGIN
D1 := TEST_FUNC(A1,B1,C1);
DBMS_OUTPUT.PUT_LINE(A1 || ' ' || B1 || ' ' || C1 || ' ' || D1);
END;
Answer Question
1 User has rated as useful.
Functions always returns One value. If you want to return more than One value, You can use the Out
parameter. Using out parameter you can get more than one value, but you cannot use that function in
Select Query.
Answer Question
The function always return a SINGLE value, which includes arrays. Check out the table functions
(pipelined), BULK_COLLECT, arrays etc... You can find plenty of examples.
Code
1. SET serveroutput ON
2. DECLARE
3. TYPE t_EmpNoArr IS VARRAY(20000) OF NUMBER(10) ;
4. v_RetVal t_EmpNoArr:= t_EmpNoArr();
5. --
6. FUNCTION retArray RETURN t_EmpNoArr
7. IS
8. v_empnoArr t_EmpNoArr:= t_EmpNoArr();
9. BEGIN
10. FOR i IN ( SELECT empno FROM emp1 )
11. LOOP
12. v_empnoArr.extend() ;
13. v_empnoArr(v_empnoArr.COUNT):= i.empno ;
14. END LOOP;
15. FOR j IN 1..v_empnoArr.COUNT() LOOP
16. DBMS_OUTPUT.PUT_LINE(v_empnoArr(j));
17. END LOOP;
18. RETURN v_empnoArr;
19. END retArray;
20. --
21. BEGIN
22. v_RetVal:= retArray();
23. END;
24. /
25.
Answer Question
1) Data Definition Language triggers: These triggers fire when you make changes to the objects in the
database like create, update or delete. They can be implemented to monitor the changes in the schema.
2) Data Manipulation Language Triggers:
3) Compound Triggers:
4) Instead-Of Triggers:
5) System or Database Event Triggers:
How to get the 25th row of a table.
Asked by: Interview Candidate | Asked on: Dec 20th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,
to get the 25th row of a table the following query can be useful
SELECT * FROM (SELECT ROWNUM r,e.* FROM emp e)
WHERE r = 25
Answer Question
1 User has rated as useful.
I will share few things regarding the solutions given for this problem,among all only two queries willwork
given by Ahmed and Pradhan.
But among these two, Ahmed's is the best solution. because its a very much optimized query.
Query given by gangadharan will not solve this problem, as it is used for Nth max. analysis.
Query given by shankar will not work, because we can not use keyword ROWNUM with Equality(=).
Well one thing to note here is that, even in Ahmed's query, r is the alias for ROWNUM. and later r has
been used with equality.=).
So remember, ROWNUM can not be used with equality but after aliasing it equality condition can be
used.
and i request my frineds here, post solution and also explain a bit how its working, because how is very
important as compared to what.
Answer Question
3 Users have rated as useful.
select * from emp where rowid=(select max(rowid) from emp where rownum<26)
Answer Question
why equality condition does'nt work with rownum, i'm giving my explanation here
the query
select * from emp where rownum=25;
it fetches first record makes it rownum 1 as it does'nt match the where criteria, the record discarded
The above query can be used to get the row of any number.
Answer Question
1 User has rated as useful.
You'd better use analytic functions, so your managers would think high of you. Besides, those fn-s are
smart and fast. I would not user ROWNUM with ORDER BY as in some examples I see here... THe
ORDER BY will reorder the rows... This is my personal preference.
Code
1. SELECT * FROM ( SELECT deptno, ename, sal
2. , ROW_NUMBER() OVER (ORDER BY sal DESC, ename) AS row_num
3. , RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) rank
4. , DENSE_RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) d_rank FROM emp )
5. WHERE row_num = 4
6. /
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
select a.deptno
from scott.emp a
, scott.emp b
where a.deptno =b.deptno
and a.rowid<>b.rowid
/
Answer Question
1 User has rated as useful.
DELETE FROM emp WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM emp GROUP BY id);
Answer Question
1 User has rated as useful.
SELECT ID
FROM func t1
WHERE ROWID = (SELECT MIN (ROWID)
FROM func WHERE ID = t1.ID)
GROUP BY id
Answer Question
1 User has rated as useful.
<
select a.DEPTNO from emp a, emp b
where a.deptno=b.deptno
and a.rowid not in (select max(rowid) from emp)
group by a.deptno;
>
Regards
Mudit
Answer Question
regards
Bambino chakma
Answer Question
Suppose if you have a table "T" with a column "C" having values 1,2,3,4,1,2,3,4.. .. ..
This will return you all distinct rows from the table
Answer Question
UNION
select * from emp b;
Answer Question
1 User has rated as useful.
Use Selfjoin in case of one table and equijoin in case of multiple tables
Answer Question
select a.no from (tablename) t1 a where rowid notin (select (max(rowid) from t1 b where a.no=b.no)
Answer Question
if u wnat to delete the duplicate values in a column u can use delete stmt.
select deptno from emp where rowid not in (select max(rowid) from emp group by deptno);
delete from emp where rowid not in(select max(rowid) from emp group by deptno);
Answer Question
FROM EMPLOYEES E
It will check for each row values if it has duplicate then using rowid min of that duplicate will be avoided
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Pragma init exception is used to associate a user defined exception with an error number and a custom
message.
Answer Question
Regards,
Anil Hadli.
Answer Question
1 User has rated as useful.
User-defined exception should be raised explicitly, While Pragma Init exception can be associated with an
Oracle inter error and be raised implicitly
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Triggers run every time when the database fields are updated
and it is overhead on system. It makes system run slower.
Disadvantage of packages:
No version control.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
If you update or delete the records in the table, at the same time, no body can update or delete the
same records which you updated or deleted because oracle lock the data which u updated or deleted.
Answer Question
You can use view for this purpose because you can set view as read only.
Answer Question
any other user or session would be able to do any insert/update to the same table only after you release
the table by commit or rollback.....
Answer Question
1 User has rated as useful.
Read only:
ALTER TABLE SALES READ ONLY;
Back to read/write:
ALTER TABLE SALES READ WRITE;
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The PLSQL Engine first makes a copy of the record and then during program executing makes a
changes to that copy.
Regards
Jegadeesan
Answer Question
NOCOPY will instruct Oracle to pass the argument as fast as possible. This can significantly enhance
performance when passing a large value.
Answer Question
If one wants to send the IN paramter too as pass by reference he could add NOCOPY
parameter....
disadvantage is when there is a change happened to the Reffered value and a rollback occurs in the
procedure the change of value would be retained.... it could not be rolled back....
When a parameter is passed as an IN variable, it is passed by reference. Since it will not change, PL/SQL
uses the passed variable in the procedure/function. When variables are passed in OUT or INOUT mode,
a new variable is define, and the value is copied to the passed variable when the procedure ends. If the
variable is a large structure such as a PL/SQL table or an array, the application could see a performance
degradation cause by copying this structure.
The NOCOPY clause tells to PL/SQL engine to pass the variable by reference, thus avoiding the cost of
copying the variable at the end of the procedure. The PL/SQL engine has requirements that must be met
before passing the variable by reference and if those requirements are not met, the NOCOPY clause will
simply be ignored by the PL/SQL engine.
Answer Question
1 User has rated as useful.
2) OUT parameter mode -This mode is used to return a value to the main block. The value of OUT
parameter can change anywhere in the program.
3) IN OUT parameter mode-This mode is used to pass values to the calling module and return a value to
the main block. The value of IN OUT parameter can change anywhere in the program.
In Call By value, the copy of actual parameter is passed to the formal parameter, So any changes to the
formal parameter doesn't affect the actual parameter.
In Call By reference, the address of actual parameter is passed to the formal parameter, so any changes
to the formal parameter will change the actual parameter also, because both of them are pointing to the
same memory location. Here no copying is required.
The IN parameter is passes by reference, so we can't change the value of IN parameter inside the
module, It acts as a constant, But the OUT and IN OUT parameters are passed by value, we can change
the values of OUT & IN OUT parameters if you use the hint NOCOPY with OUT Parameter and IN OUT
Parameter then ::: call by reference
Answer Question
2 Users have rated as useful.
sipsin: Actually the reverse is true. Usually the IN parameter is passed by reference and the OUT/IN OUT
parameters are passed by value.
Answer Question
Actually it is more useful when we are passing a large record or a large table.
Thanks
Saravanan.P
Asked by: ily_saravanan | Member Since Oct-2006 | Asked on: Mar 19th, 2007
View all questions by ily_saravanan View all answers by ily_saravanan
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
4 rows updated.
SQL> select * from cug;
ID_CUG ID_B TYPE
---------- ---------- ----------
0 0 0
1 0 2
2 0 2
3 2 3
4 2 3
5 2 4
6 2 4
Next we delete the "Leader" with ID_CUG = 2. All childs must be deleted automatically with the DELETE
CASCADE.
SQL> select * from cug;
ID_CUG ID_B TYPE
---------- ---------- ----------
0 0 0
1 0 2
Everything looks fine - cool isn't it ?
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
array is set of values of same datatype.. where as tables can store values of diff datatypes.. also tables
has no upper limit where as arrays has.
Answer Question
Pl/sql tables can not be stored in database where as varrays can be stored in database.
We can use negetive index for pl/sql tables. In varrays negetive index is not allowed.
In pl/sql tables data need not be stored in consecutive rows. Varrays are dense and retain their order
while storing in database.
You can not perform DML operations on PL/SQL table . DML operations can be performed on Varrays.
In PL/SQL if we write select statement with INTO clause it may return two
exceptions NO_DATA_FOUND or TOO_MANY_ROW . To do you avoid these
execeptions. How do you write SQL statement in alternative way?
Asked by: ddkdhar | Member Since Jun-2006 | Asked on: Mar 1st, 2007
View all questions by ddkdhar View all answers by ddkdhar
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
hi all,
i.e
-------------
------------
----------
Exception
when NO_DATA_FOUND then
Dbms_output.put_line('No Record');
---------
-----------
-------------
Regards,
Nikhil.
Answer Question
There is no solution for NO_DATA_FOUND else you handle it using Exception block as i
do above...
uses "=" operator then may be there is Too_many_rows exception, to avoid this
i.e
Thanks,
Nikhil.
Answer Question
Yes you can handle Too_Many_Rows exception when you are writing into a PL/SQL block SELECT...INTO
statement.
Regards.
Mala
Answer Question
Answer Question
In cursors if NO_DATA_FOUND then it will not raise any exception. In cursors you need to handle it using
%FOUND or %NOTFOUND cursor attributes.
Answer Question
SELECT count(rowid)
into v_count
from tables
where conditions.
if(v_count = 1) then
SELECT column
into v_column
from tables
where conditions;
else
--Select statement not executed because it will throw exception
v_column=dummy_value;
end if;
Answer Question
1) NO_DATA_FOUND - is raised only for "select into" statements when the where clause of the query
does not match any rows.
2)TOO_MANY_rows - is raised if a "select into" statement matches more than one row.
Solution for 1- In the exception section use a handlerlike this "when no_data_found theninsert into
log_error ('no matching data')".
for 2) - This is a result of poor design or programming. One need to use a cursor.
Without closing the cursor, If you want to open it what will happen. If error, get
what is the error?
Asked by: ddkdhar | Member Since Jun-2006 | Asked on: Mar 1st, 2007
View all questions by ddkdhar View all answers by ddkdhar
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
If you reopen a cursor without closing it first,PL/SQL raises the predefined exception
CURSOR_ALREADY_OPEN.
Answer Question
2 Users have rated as useful.
It is legal to open an already opened cursor. When we try to open an already opened cursor, the cursor
when it is initially opened is automatically closed and again opened.
Answer Question
CURSOR_ALREADY_OPEN ORA-06511 An attempt was made to open a cursor that was already open.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
HI,
IN :
is default Param and always Pass By Value, in case of IN Parma Default
value is possible
i.e
Create or replace procedure Cal_Comm
(did in emp.deptno%type Default 20)
is possible.
OUT , IN OUT :
Tanx
NIKHIL
Answer Question
Can anyone please explain the same. The above two answers are contradictory.
Answer Question
IN parameters are passed by reference, so the value cannot be changed in the procedure and functions.
Out and IN-OUT parameters are passed by value, so the values can be changed inthe procedures and
fucnctions.
Answer Question
1 User has rated as useful.
INOUT :- actual parameter is passed by value (a copy of the value is passed in and out) unless NOCOPY
is specified
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,
#1
Use PRAGMA AUTONOMOUS_TRANSACTION;
Code:
Create or replace procedure Create_tab
As
PRAGMA AUTONOMOUS_TRANSACTION;
Begin
EXECUTE IMMEDIATE
‘Create TABLE ProcT(col1 number(2), col2 varchar2(10))’;
End;
#2
Code:
(TabName in varchar2)
as
V_cursor INTEGER;
Ddl_Execute INTEGER;
begin
V_cursor:=Dbms_sql.Open_cursor;
(10))',Dbms_sql.native);
Ddl_Execute:=dbms_sql.Execute(V_cursor);
Dbms_output.put_line(TabName||' Created.');
If Dbms_sql.Is_open(V_cursor) then
Dbms_sql.Close_cursor(V_Cursor);
end if;
Exception
Dbms_output.put_line(sqlerrm);
End Dynamic_Tab;
Regards,
Nikhil (iflex).
Explain, Is it possible to have same name for package and the procedure in that
package.
Asked by: Interview Candidate | Asked on: Feb 25th, 2007
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Yes, its possible to have same name for package and the procedure in that package.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
A dense_rank fn is similar to Rank fn except for a difference that it does not skip sequential ranking
numbers. If two values are the same and have same rank for ex. 3, then in dense_rank fn the next non
duplicate value will be ranked 4. In normal Rank fn, the next non duplicate value would have
been ranked 5 .
Answer Question
1 User has rated as useful.
select dense_rank,rank,sal
from emps
order by sal desc
dense_rank|rank|sal
1 1 10000
2 2 5000
2 2 5000
4 3 4000
In the above example you can see that in the dense_rank function if there is a tie then the next position
will be skipped and in the rank function the count start from the next position.
what is diff between strong and weak ref cursors
Asked by: ddkdhar | Member Since Jun-2006 | Asked on: Feb 16th, 2007
View all questions by ddkdhar View all answers by ddkdhar
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
DECLARE
TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; -- strong
TYPE GenericCurTyp IS REF CURSOR; -- weak
Answer Question
Strong Ref cursor type is less Error prone, because oracle already knows what type you are going to
return as compare to weak ref type.
Answer Question
strong ref cursor return value, but seek ref cursor it can't return any value
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
LOB datatypes can be used to store blocks of unstructured data like graphic images, video, audio, etc
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
There is no limitation on the number of Subprograms in the package, but there is a limitation on the
compiled file size in the database .
what is the order of execution if there is a statement level and row level trigger on
a same table?
Asked by: Interview Candidate | Asked on: Jan 30th, 2007
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
3) Actual Statement
before insert on c
declare
vnum number;
begin
dbms_output.put_line('c_b4sttmnt');
end;
after insert on c
declare
vnum number;
begin
dbms_output.put_line('c_aftrsttmnt');
end;
after insert on c
declare
vnum number;
begin
dbms_output.put_line('c_aftrrow');
end;
before insert on c
declare
vnum number;
begin
dbms_output.put_line('c_b4row');
end;
Please execute the following command which will fail after first 3 triggers.
c_b4sttmnt
c_b4row
c_aftrrow
ORA-02291: integrity constraint (STAGE.SYS_C0049041) violated - parent key not
found
Regards
- BHAILOGONLINE
Answer Question
Answer Question
and
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Yes you can have . This is because the triggers dont share the same namespace for tables.whereas
funtions,procedures,tables etc share the same namespace.so they cant have the same name
Answer Question
Yes you can have..but you cannot predict the order of the execution.
Answer Question
Nikhil - i-flex
Answer Question
for example:
create or replace trigger trigg1
before delete on emp
begin
raise_application_error(-20001,'Delete not allowed');
end;
Prabha Sharma
Answer Question
2 Users have rated as useful.
Ritesh
Answer Question
2 Users have rated as useful.
The triggers will be fired on the basis of TimeStamp of their creation in Data Dictionary. The trigger with
latest timestamp will be fired at last.
Regards,
Manish kumar
Answer Question
The trigger which has the latest timestamp will be executed first and then followed by the others in the
order of their creation :)
Answer Question
1 User has rated as useful.
say ::
m trigger ---created last fires first.
a trigger
z trigger
ttt trigger
tt trigger-- created first fires last
Answer Question
The trigger which is newly created will be fired first then the old trigger
Answer Question
but 11g we are having a feature follows clause,by using this we have to control the execution of triggers
explicitly by the developer,
yes we can have 2 triggers with same body but with different names.
What will happen to an anonymus block,if there is no statement inside the block?
eg:-
declare
begin
end;
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
An error is encountered.
Answer Question
If you do not want any executable statement within the begin-end block, you can include a null statment.
eg:
begin
null;
end;
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
cursor is basically a pointer as it's like a address of virtual memory which is being used storage related
tosql query & is made free after the values from this memory is being used.
what happens when commit is given in executable section and an error occurs
?please tell me what happens if exception block is committed at the last?
Asked by: Interview Candidate | Asked on: Jan 8th, 2007
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
all the transactions done by that executable section will be rolled back
Answer Question
well the answer is, what ever done in executable section will be lost. u can see the exapmle:created table
d as below:SQL > create table d ( sl number(4), name varchar2(5));now do the following
operation:SQL> begin insert into d values ('1223123123','geekinterview'); --making insert to fail here
commit; exception --catching the exception here when others then commit; end; /PL/SQL procedure
successfully completed.now if we use :SQL> select * from d; no rows selectedso even the pl/sql
procedure completed successfully no values were saved in d.this is one case where we are giving invalid
values for both the fields(in insert stmt.). now see the below procedure:SQL> begin insert into d values
('1223123123','RSY'); --first value is incorrect, second is correct one commit; exception when others then
commit; end; /PL/SQL procedure successfully completed.SQL> select * from d; no rows selectedeven in
this case, nothinghas been inserted in table d. even though value for name field is a valid data.now there
is one possible case:SQL> begin insert into d values ('123','RSY'); --both values are correct commit; --
commiting first time insert into d values ('1223123123','RSY'); --entering values to fail insert commit;
exception --handling exception when others then commit; end; /PL/SQL procedure successfully
completed.SQL> select * from d; SL NAME--------- ----- 123 RSYso here the first insert has been
committed, but at the time of second insert the condition fails, so second insert is roll backed. but it will
not affect data that has been already committed.ok take carecheersRSY
Answer Question
hi ,again am posting the same answer, i do not know why the answer is not displayed with proper
formatting. ok once more i will try:well the answer is, what ever done in executable section will be lost. u
can see the exapmle:created table d as below:SQL> create table d ( sl number(4), name
varchar2(5));now do the following operation:SQL> begin insert into d values
('1223123123','geekinterview'); --making insert to fail here commit; exception --catching the exception
here when others then commit; end; /PL/SQL procedure successfully completed.now if we use :SQL>
select * from d; no rows selectedso even the pl/sql procedure completed successfully no values were
saved in d.this is one case where we are giving invalid values for both the fields(in insert stmt.). now see
the below procedure:SQL> begin insert into d values ('1223123123','RSY'); --first value is incorrect,
second is correct one commit; exception when others then commit; end; /PL/SQL procedure successfully
completed.SQL> select * from d; no rows selectedeven in this case, nothinghas been inserted in table d.
even though value for name field is a valid data.now there is one possible case:SQL> begin insert into d
values ('123','RSY'); --both values are correct commit; --commiting first time insert into d values
('1223123123','RSY'); --entering values to fail insert commit; exception --handling exception when others
then commit; end; /PL/SQL procedure successfully completed.SQL> select * from d; SL NAME --------- ---
-- 123 RSYso here the first insert has been committed, but at the time of second insert the condition fails,
so second insert is roll backed. but it will not affect data that has been already committed.ok take
carecheersRSY
Answer Question
Whenever the exception is raised ..all the transaction made before will be commited. If the exception is
not raised then all the transaction will be rolled back.
Answer Question
2 Users have rated as useful.
commit;
end;
/
PL/SQL procedure successfully completed.
now if we use :
SQL> select * from d;
no rows selected so even the pl/sql procedure completed successfully no values were saved in d.
this is one case where we are giving invalid values for both the fields in insert stmt.).
commit;
end;
/
PL/SQL procedure successfully completed.
SQL> select * from d;
no rows selected even in this case, nothing has been inserted in table d.
even though value for name field is a valid data. now there is one possible case:
SQL> begin insert into d values ('123','RSY');
--both values are correct commit;
end;
/
PL/SQL procedure successfully completed.
SQL> select * from d;
SL NAME
--------- -----
123 RSY
so here the first insert has been committed, but at the time of second insert the condition fails, so second
insert is roll backed. but it will not affect data that has been already committed.
ok take care
cheers
RSY
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The basic reason for this error is the way Oracle manages a read consistent view of data. The error is
encountered when a row-level trigger accesses the same table on which it is based, while executing. The
table is said to be mutating.
Answer Question
Say for exampleThere is a before insert row level trigger T1 on the table empInside the trigger if you give
Select Count(*) from Emp, then mutating table error will be raised. This is because you are trying to
access the emp that is being updated by the same trigger. In the same example if you change row level
to statement this error will not be raised.
Answer Question
A table which is being updated is a mutating table, performing any DML operations or querying on a
mutating table leads to a mutating error. This can be possible in triggers or in funtions that are used in
expressions.
Answer Question
2 Users have rated as useful.
Hey All,
see you have row level trigger on table with before/after timing, now in you
Based , then there is Mutating of Trigger Error. Since oracle can`t proccess
Bye.............
Nikhil. - i-flex
Answer Question
we can also make use of compound trigger (new feature in 11 g to avoid mutating error)
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Set Timing onSelect * from Emp;You will get the time displayed.
Answer Question
we can find the time of execution of a sql statement using dbms_utility.get_time package
eg:declare
v1 integer;
v2 number;
begin
v1:=dbms_utility.get_time;
dbms_output.put_line(v1);
select count(*) into v2 from employee;
v1:=dbms_utility.get_time;
dbms_output.put_line(v1);
end;
/
Answer Question
This will show how much time your query took for the execution.
What is materialized view?
Asked by: Interview Candidate | Asked on: Dec 20th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
A materialized view is a database object that contains the results of a query. They are local copies of data
located remotely, or are used to create summary tables based on aggregations of a table's data.
Materialized views, which store data based on remote tables are also, know as snapshots.A materialized
view can query tables, views, and other materialized views. Collectively these are called master tables (a
replication term) or detail tables (a data warehouse term).
Answer Question
2 Users have rated as useful.
A materialized view or snapshot contains the results of a query of one or more tables, each of which may
be located on the same or on a remote database. Materialized viwes allows to create replications of
tables of remote data with a read-only privillage on the copy. When a materialized view is created, Oracle
creates one table and index, and in the same schema of the materialized view.
Answer Question
1 User has rated as useful.
A materialized view is like a query with a result that is materialized and stored in a table. When a user
query is found compatible with the query associated with a materialized view, the user query can be
rewritten in terms of the materialized view. This technique improves the execution of the user query,
because most of the query result has been precomputed. The query transformer looks for any
materialized views that are compatible with the user query and selects one or more materialized views to
rewrite the user query. The use of materialized views to rewrite a query is cost-based. That is, the query
is not rewritten if the plan generated without the materialized views has a lower cost than the plan
generated with the materialized views.
Answer Question
in addition to te previous posts, unlike a View,which refreshes automatically if the underlying base table
data is changed, the data in a Materialized view needs o be refreshed explicitly with the help of a
dbms_job.Thanks.
Answer Question
Materialized views are schema objects that can be used to summarize, precompute, replicate, and
distribute data. E.g. to construct a data warehouse.
Answer Question
A materialized view have a physical memory where it can store the result of query which are combination
in joining of one or more table and view it retrieve a faster result. when we want to refresh the data
which are coming from diffrent application so it retrive the fast result. its a benefit of materialized view.
Answer Question
Refresh intervals represents, how the frequently the materialized view has to be refreshed. Refresh
modes are
1. Complete
2. Fast
3. Force
4. Uncommit
5. On demand
6. Differed
Answer Question
Materialized views are objects that are used in base table that can be Summarized Group, and
aggregated with the base table.This materialized views are used in data-ware housing and decision
support system.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Autonomous transactions are independent transactions that can be called from within another
transaction. An autonomous transaction lets you leave the context of the calling transaction, perform
some SQL operations, commit or undo those operations, and then return to the calling transaction's
context and continue with that transaction.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
I am sorry I didn't notice the second part of your question. This is used with the declaration of OUT
parameter.eq. PROCEDURE my_proc (param1 IN varchar2, param2 OUT NOCOPY varchar2, param3 IN
OUT NOCOPY varchar2)
Answer Question
For better understanding of NOCOPY parameter, I will suggest u to run the following code and see the
result.
DECLARE
n NUMBER := 10;
PROCEDURE do_something (
n1 IN NUMBER,
n2 IN OUT NUMBER,
n3 IN OUT NOCOPY NUMBER) IS
BEGIN
n2 := 20;
DBMS_OUTPUT.PUT_LINE(n1); -- prints 10
n3 := 30;
DBMS_OUTPUT.PUT_LINE(n1); -- prints 30
END;
BEGIN
do_something(n, n, n);
DBMS_OUTPUT.PUT_LINE(n); -- prints 20
END;
Thanks & Regards,
Ritesh Kumar.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Advantages
------------
Modular approach, Encapsulation/hiding of business logic, security, performance improvement, reusability
Disadvantages
-------------
Cant think of any
Answer Question
1 User has rated as useful.
Login to rate this answer.
sunnyjsr
Answered On : Dec 3rd, 2006
View all answers by sunnyjsr
Disadvantages of Package - More memory may be required on the Oracle database server when using
Oracle PL/SQL packages as the whole package is loaded into memory as soon as any object in the
package is accessed.
Answer Question
1 User has rated as useful.
Disadvantages: Updating one of the functions/procedures will invalid other objects which use different
functions/procedures since whole package is needed to be compiled.
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Database triggers are executed in response to particular events on tables in a databaseSchema triggers
are fired when schema objects (tables) are modified. It can be like before create, later,drop
Answer Question
Login to rate this answer.
srietl
Answered On : Oct 30th, 2006
View all answers by srietl
May be the question is like this 'Whats the diff. between database triggers on database or schema?
Database triggers can be system triggers on a database or a schema.
With a database,triggers fire for each event for all users...
With a schema,triggers fire for each event for that specific user...
Answer Question
1 User has rated as useful.
A trigger defined at the database level fires for all users, and
A trigger defined at the schema or table level fires only when the triggering event involves that
schema or table.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Database Server have many schemas, and users, it has only one instance for the organisation, or lets say
its an instance of the data with all schema infowhereas the data dictionary contains raw data, of the
entire data of the database alongwith compiled code of all packages, procedures, funtions and the all
tables.infact the database server stores everything in raw format in the datadictionary they are not diff
but areone and the same
Answer Question
Database server is base on which everything resides,It Contains all the schemas,triggers,views etc..
Data Dictionary contains meta data information about each and every schemas object like tables
procedures..etc.
Answer Question
2 Users have rated as useful.
HiDatabase server is a server on which the instance of oracle as server runs..whereas datadictionary is
the collection of information about all those objects like tables indexes views triggers etc in a database..
Answer Question
Database Server:
It's contains the collection of objects (Table,procedure,trigger,sequence,index,etc)
it's also contains the Schema and user details
we can view the details which are in the Database server
DB dictionary:
It's contains the meta data format of all schema ,user information and object information also
Its contains the data is in non readable format.
Regards,
MPS
Bangalore
Answer Question
Hi, How do we display the column values of a table using cursors without
knowing the column names inside the loop?
Asked by: Interview Candidate | Asked on: Oct 19th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
I do not think so. You can not retrive the values from a cursor with OUT KNOWING THE COLUMN
NAME. You can not have (same name)/ (No Name) for all in a family.
Answer Question
1 User has rated as useful.
Declare a variable using PL/SQL %ROWTPE ( l_Record EMP%ROWTYPE)In the cursor, you can say ..
cursor cursorname is select * from emp..Open cursor; loop .. fetch cursorname into l_Record.. Display
the values from l_Record using dbms_output.put_line.Close the loop and cursor
Answer Question
Hi Gopal
Can u give a example please .
Answer Question
You can not retrive the values from a cursor with OUT KNOWING THE COLUMN NAME
Answer Question
I Don't think so, If you are trying to populate the data using Records, then also you should know name
of the columns from the table or select query of the cursor.
Answer Question
No.its not possible to fetch column value from a cursor without knowing the column name,there is
nothing to do with cursor,cursor is nothing but explicitly created memory area to fetch record, using sql
query itself..and its not possible to retrieve any value without knowing column name,if it is not like that,
plz expalin with an example..
Answer Question
For ex.
then you will get first clomun name of emp table; ex. for in 1..2 loop select cname into cname1 from col
where col=i and tname='emp';
end loop;
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Flahsback is used to take your database at old state like a system restore in windows. No DDL and DML is
allowed when database is in flashback condition.
user should have execute permission on dbms_flashback package
for example:
at 1030 am
from scott user : delete from emp;
commit;
at 1040 am I want all my data from emp table then ?
declare
cursor c1 is select * from emp;
emp_cur emp%rowtype;
begin
dbms_flashback.enable_at_time(sysdate - 15/1440);
open c1;
dbms_flashback.disable;
loop
fetch c1 into emp_cur;
exit when c1%notfound;
insert into emp values(emp_cur.empno, emp_cur.ename, emp_cur.job,
emp_cur.mgr,emp_cur.hiredate, emp_cur.sal, emp_cur.comm,
emp_cur.deptno);
end loop;
commit;
end;
/
select * from emp;
14 rows selected
Answer Question
3 Users have rated as useful.
Thank u Rampratap.
Answer Question
Hi,
Can anyone tell me the difference between instead of trigger, database trigger,
and schema trigger?
Thanks.
Asked by: Interview Candidate | Asked on: Oct 18th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Showing Answers 1 - 5 of 5 Answers
sunnyjsr
Answered On : Oct 21st, 2006
View all answers by sunnyjsr
INSTEAD OF Trigger control operation on view , not table. They can be used to make non-updateable
views updateable and to override the behvior of view that are updateable.
Database triggers fire whenever the database startup or is shutdown, whenever a user logs on or log off,
and whenever an oracle error occurs. these tigger provide a means of tracking activity in the database
Answer Question
Instead of trigger : A view cannot be updated , so if the user tries to update a view, then this trigger can
be used , where we can write the code so that the data will be updated in the table, from which the view
was created. Database trigger : this trigger will be fired when a database event ( dml operation ) occurs
in the database table, like insert , update or delete. System triggers : this trigger will fire for database
events like dtartup / shutdown of the server, logon / logoff of the user, and server errors ... and also for
the ddl events, like alter, drop, truncate etc.
Answer Question
1 User has rated as useful.
Hi
if we have created a view that is based on join codition then its not possibe to apply dml operations like
insert, update and delete on that view. So what we can do is we can create instead off trigger and
perform dml operations on the view.
Database Vs Schema trigger:
consider these three triggers
create or replace trigger trig_usrA_conn
after logon on schema
Begin
insert into example.temp_table values (1,' user A connection fired');
End;
create or replace trigger trig_usrB_conn
after logon on schema
Begin
insert into example.temp_table values(2.'user B connection fired');
End;
create or replace trigger trig_All_conn
after logon on database
Begin
insert into example.temp_table values(3,' All connection fired');
End;
we have created two schema trigger for usera A and B and then created a database trigger. The
Database and Schema Keywords determine the level for a given system trigger.
Now you can connect to the database as usera A and then user B and example database. The after logon
trigger on the schema fires first and then after logon trigger to the database
connect userA/userA
connect userB/userB
connect example/example
Answer Question
Suppose I have 2 triggers on table T, tr1- a before insert trigger & tr2- a before
update trigger.
tr1 has update (T) statement inside body of tr1
and
tr2 has insert (T) statement inside body of tr2
Now, I'm tring to insert a row into T.
What will hppn??
Asked by: shamim909 | Member Since Apr-2006 | Asked on: Oct 13th, 2006
View all questions by shamim909 View all answers by shamim909
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
try it,
it really works!!
Answer Question
It(autonomous transaction) will work but it'll not satisfy your business requirement. Mutating error is not
actually an error but Oracle has provided this feauture to do away with any side effects due to the bad
application design. Therefore mutaing rror means, sometning is wrong with the application design.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Showing Answers 1 - 6 of 6 Answers
Rajeshwaran
Answered On : Oct 12th, 2006
%Rowtype means associating a single variable to a entire row.(It is one way of Declaring a composite
plsql datatype "RECORD")
%type means associating a single variable to a particular column in table.
both %Rowtype and %type declarations are known as Anchored Declarations in plsql .
Answer Question
2 Users have rated as useful.
%RowType provides the records type the represent a entire row of a table or view or column select in
the cursor
%Type provides the data type of a variable or a database column to that variable.
Sunny Singh
9860229246
Answer Question
%RowType provides the full records values in one variable, and if in a table any column is added then
also your proc/function will not fail, that variable will hold the reference for new column also.
example:
v_rec emp%rowtype ;
%Type provides the data type of a column of a table
v_empno emp.empno%type;
use of %type, %rowtype makes your proc/function more effective and efficient.
Answer Question
E.g
v_emp emp%rorwtype
v_ename ename%type
Answer Question
Login to rate this answer.
Radha
Answered On : Jul 14th, 2011
We use %type and %rowtype in PL/SQL programming part.
%Type: The variable will assign the datatype which contains in the column of that particular table we
mentioned.
Ex: v_eno employee.eno%type;
Here V_eno is a variable which is assigned the data type of eno column of employee table.
%rowtype is used when we have to make a single variable which can have similar datatype values of a
record i.e
it can handle different datatype at a time.
what is difference between Cursor and Ref Cursor. Please give example.
Asked by: Interview Candidate | Asked on: Oct 8th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Cursor is static one and ref cursor is dynamic with return type.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Ya, we can create table with procedure by using 'EXECUTE IMMEDIATE' command.
Mutating error:- occurs when row level trigger accesses same table on which it is based while executing
or the table currently being modified by the DML statements.
Answer Question
HI,
table can be created by using either dbms_sql or EXECUTE_IMMEDIATE in procedure or function.
Answer Question
DECLARE
BEGIN
EXECUTE IMMEDIATE 'create table employee(empno number(3),ename varchar2(10))';
END;
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Answer Question
1 User has rated as useful.
insted of triggers: They provide a transparent way of modifying view that can't be modified directly
through SQL ,DML statement.
Answer Question
Hi Shashank,
Can you explain instead off trigger, DML Trigger and views.
.
Answer Question
then oracle will create datablock for 2 extra spaces.so while querying it must read data from two blocks.
so performance is less for varchar2
Suppose thr are 10 DMLs(insert,update,delete ) in the main section of the PL/SQL
block .The exception in them is handled as a whole in the exception handling
section .....The error may occur in any of this DMLs ,so how can we understand
that which DML has failed ??
Asked by: Interview Candidate | Asked on: Sep 24th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
i think u can use show error option and come to know the error........
Answer Question
That you need to manipulate programtically. Like you can declare a variable called some counter. And
after each statement u increase the value of that counter variable. In the exception block u can
conditionally print the error msg on your own as you know the value of the variable and in which sql
statement u got the exception.
Answer Question
using dbms_utility.format_call_stack you can know the row where the error occured
Answer Question
update table1
set column1='value1'
where column2='condition 2'
commit;
DBMS_OUTPUT.PUT_LINE(table 1 update completed);
update table2
set column2='value2'
where column2='condition 3'
commit;
DBMS_OUTPUT.PUT_LINE(table2 update completed);
If any error comes then the output statement after that update will not be
present in the log
Answer Question
Other method:
begin
location :=1;
dml1
location :=2;
dml2
exception
when others than
dbms_output('error at location ' || location || sqlerrm);
end;
Answer Question
DML 1
'
'
'
'
'
DML 10
exception
when others than
dbms_output('error at location '||dbms_utility.format_error_backtrace);
end;
dbms_utility.format_error_backtrace gives line number at which error has occured and its reason also.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
session variable can not be declared in package, variable declared in package are called global variables.
create package mypack is
num number := 7;
num2 number;
end ;
here num, num2 are global variable
when ever you wnt to use them. you have to use mypack.num or mypack.num2
where as session variable are declared like:
variable res number;
now when ever in current session you wnt to use res , use :res
":" indicates the session variable
Answer Question
2 Users have rated as useful.
SYS_CONTEXT('CLIENTCONTEXT','M')
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
You can use the following e.g.1. SELECT * FROM ( SELECT deptno, ename , sal , ROW_NUMBER() OVER
( PARTITION BY deptno ORDER BY sal DESC ) Top3 FROM emp )WHERE Top3 <= 3/2. This will give
distinct values.SELECT * FROM ( SELECT deptno, ename , sal , DENSE_RANK) OVER ( PARTITION BY
deptno ORDER BY sal DESC ) Top3 FROM emp )WHERE Top3 <= 3/
Answer Question
1 User has rated as useful.
the query is select * from sample where rownum=(select max(rownum) from sample)
Answer Question
select * from ( select rownum r, sal,name from (select * from emp order by sal)) where r=
You need to give all column names in first inline view.
Answer Question
We can use dense_rank() built in. It will rank the result set based on the column which is given in the
over() clause.
For ex) to get the 7th highest salary we can use the following query.
select * from(
select empno,ename,salary,dense_rank() over(order by salary desc) r
from emp )where r=7
I have used this in 10g..i am sure about the below versions.
Answer Question
1 User has rated as useful.
select max(sal) from emp a where &n = (select count(distinct sal) from emp where sal >= a.sal);
Answer Question
If we have a table EMP and having data as, if we want second highest sal i.e 5000 the the query will be:
Code
1. EMPNO ENAME SAL
2. 1 A 5000
3. 2 B 2000
4. 3 C 10000
5.
6. SELECT MIN(SAL) FROM (SELECT * FROM EMP ORDER BY SAL DESC)
7. WHERE ROWNUM <=2
8.
Same as nth highest query we need to put that number instead of 2.
Answer Question
It is better to use analytic functions these days as they are faster and smarter and your managers will
think high of you...
Code
1. Top n-paid IN ALL Depts - changer the orde BY dept AND sal DESC IF ant TO find
out top paid IN each dept:
2. SELECT * FROM ( SELECT deptno, ename, sal
3. , ROW_NUMBER() OVER (ORDER BY sal DESC, ename) AS row_num
4. , RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) rank
5. , DENSE_RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) d_rank
6. FROM emp )
7. --WHERE row_num <= 4
8. /
Answer Question
This is incorrect. It will not return anything. One of the possible answer is
Code
1. SELECT salary FROM (SELECT rownum n, a.salary
2. FROM
3. (SELECT DISTINCT salary FROM person ORDER BY salary ) a)
4. WHERE n = 5 ;
Answer Question
This is what I did. I specified n = 1 which means I want the highest salary. then I put the NULL values
for this record in salary column. The record with NULL value always shows me as the highest salaried
employee which is incorrect.
Answer Question
use
Code
1. NVL(a.sal,0)<= NVL(b.sal,0)
Hi Friends!!
Can anybody answer what are the constraints on Mutating tables? How to remove
the mutating errors in triggers? Urgent plzzzzzzzzzzzzzzzz
Thanks in Advance..
Thanks&Regds
Ramki,TCS
Asked by: Interview Candidate | Asked on: Aug 30th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi Friend
Trigger Mutating will araise, when u want to do more than one DML operation on a table u will get
Trigger Mutation.
For example
U have table Stud with Sno, Mark1, Mark2, total,Avg fields.
U write a trigger Like below
Create or Replace Trigger Stud_Trig AFTER INSERT ON STUD FOR EACH ROW
begin
Update Stud SET total=:NEW.mark1 + :NEW.mark2, Avg = (:New.mark1 + :new.mark2) / 2 where sno
= :new.sno;
end;
Here u will get trigger Mutating.
The Trigger Mutating also appear in another time. I am not sure abt that time
I will work out and give the sample to u.
Regards
badhu
Answer Question
I got rid of same kind of error while writing a trigger. I wrote a new function using AUTONMOUS
TRANSACTION keyword within it and called that function from the trigger. It worked for me. Hope it
works for you as well.
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
by declaring this cursor we can update the table emp through z,means wo not need to write table name
for updation,it may be only by "z".
Answer Question
No error. Everthing is fine. Once commit, the only thing happened is the table got unlocked.
Answer Question
Answer Question
3 Users have rated as useful.
No error. Everthing is fine. Once commit, the only thing happened is the table got unlocked.
Table is locked until the table is updated or deleted
Answer Question
NO ERROR..
Answer Question
SQL> start e1
Declare * ERROR at line 1: ORA-01002: fetch out of sequence ORA-06512: at line 8
Reason: This error means that a fetch has been attempted from a cursor which is no longer valid.
Here the main reason of this error is
"the cursor has been opened with the FOR UPDATE clause, fetching after a COMMIT has been issued will
returning the error.
Action: Do not issue a COMMIT inside a fetch loop for a cursor that has been opened FOR UPDATE
Answer Question
1 User has rated as useful.
Thanks,
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi RamaKrishna,Currently, cursor variables are subject to the following restrictions:You cannot declare
cursor variables in a package spec. For example, the following declaration is not allowed:CREATE
PACKAGE emp_stuff AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; emp_cv
EmpCurTyp; -- not allowedEND emp_stuff;You cannot pass cursor variables to a procedure that is called
through a database link.If you pass a host cursor variable to PL/SQL, you cannot fetch from it on the
server side unless you also open it there on the same server call.You cannot use comparison operators to
test cursor variables for equality, inequality, or nullity.You cannot assign nulls to a cursor
variable.Database columns cannot store the values of cursor variables. There is no equivalent type to use
in a CREATE TABLE statement.You cannot store cursor variables in an associative array, nested table, or
varray.Cursors and cursor variables are not interoperable; that is, you cannot use one where the other is
expected. For example, you cannot reference a cursor variable in a cursor FOR
loop.Regardslatha,Bangalore,TCS
Answer Question
3 Users have rated as useful.
hi friend
cursor variable can't use with dynamic sql.
cursor variable can't use with in package because it is not having persistent state.
nulls can't assinged to cursor variable.
remote procedure can't accept cursor variable
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Yes,
we can declare a column with above condition.
table created successfully.
Answer Question
1 User has rated as useful.
Yes ,such declaration is possible .Explaining with example .1.number(9,11) means there are 11 digits
after decimal .However as the max precision is 9 so the rest are zero padded .Like
0.009999999992.number(9,-11) means that there are 9 digits whereas the rest is zero padded towards
left of the decimal point Like 99999999900000000000.0
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Alter table
disable all trigger;
Answer Question
How to avoid using cursors? What to use instead of cursor and in what cases to
do so?
Asked by: moviefan456 | Member Since Aug-2006 | Asked on: Aug 9th, 2006
View all questions by moviefan456
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
hai
just use subquery in for clause
ex:
for emprec in (select * from emp)
loop
dbms_output.put_line(emprec.empno);
end loop;
no exit statement needed
implicit open,fetch,close occurs
try this and send me the reply on [email protected]
Answer Question
2 Users have rated as useful.
Thanks.
Venkat
Answer Question
Login to rate this answer.
Venkat9999
Answered On : Sep 21st, 2006
if you need to perform manipulations from the output of the select statement which results multiple rows
,the cursor need to be used.
Answer Question
Well there may be several ways for not to use a cursor. But a good programming practice suggests the
use of cursors as much as possible for performance and efficiency purpose.
Answer Question
insted of using cursor we will use attribute data types %type and %rowtype to load data in pl/sql
Answer Question
Login to rate this answer.
krishnaindia2007
Answered On : May 8th, 2008
View all answers by krishnaindia2007
You can use bulk binding to avoid cursors. It improves performance by minimizing context switches sql
and pl/sql. When you are hadling large volume of data then better to use bulk binding.
Answer Question
1 User has rated as useful.
How we can create a table in PL/SQL block. insert records into it??? is it possible
by some procedure or function?? please give example...
Asked by: Interview Candidate | Asked on: Aug 8th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
hi , you can run DDL (create) command in PL/SQL through EXECUTE IMMEDIATE command.
Answer Question
1 User has rated as useful.
No, I tried this out but.... it give error...You just try it and give me the synatx and the code that u
executed
Answer Question
yes we can create a table in the PLSQL block very easly with the help of procedure
hint : here abcd is the procedure name of the stored procedure
create or replace procedure abcd is
begin
create table stud1(sno number(3),sname varchar2(10))
/
end abcd;
/
after that write a program to call the stored procedure
begin
abcd;
end;
/
Answer Question
Dear friends...
Whatever the programme u r writing thea .. is that working... NOOOOOOOO.. so plz try it then
answer.... cause in Rams programme the procedure is created but not creating any table... and chanti....
this is impossible... go through the machine...
Regards
Dinesh
Answer Question
Hi,
Whatever Ram has given is the correct approach only. However, if you execute the procedure, you may
be left with no table created. That may be because you won't have sufficient privileges. Look down how I
tried to careate a procedure as Ram told and how I executed that and what problem I faced and how I
rectified that.
SQL > conn maria/maria;
Connected.
SQL> set serverout on;
SQL> CREATE OR REPLACE PROCEDURE ddl_create_proc (p_table_name IN VARCHAR2)
2
3 AS
4
5 l_stmt VARCHAR2(200);
6
7 BEGIN
8
9 DBMS_OUTPUT.put_line('STARTING ');
10
11 l_stmt := 'create table '|| p_table_name || ' as (select * from emp )';
12
13 execute IMMEDIATE l_stmt;
14
15 DBMS_OUTPUT.put_line('end ');
16
17 EXCEPTION
18
19 WHEN OTHERS THEN
20
21 DBMS_OUTPUT.put_line('exception '||SQLERRM || 'message'||sqlcode);
22
23 END;
24 /
Procedure created.
SQL> set serverout on
SQL> exec ddl_create_proc('tony_emp');
STARTING
exception ORA-01031: insufficient privilegesmessage-1031
PL/SQL procedure successfully completed.
SQL> conn system/manager;
Connected.
SQL> grant create table to maria identified by maria;
Grant succeeded.
SQL> conn maria/maria;
Connected.
SQL> set serverout on
SQL> exec ddl_create_proc('tony_emp');
STARTING
end
PL/SQL procedure successfully completed.
SQL> select * from tab;
TNAME TABTYPE CLUSTERID
------------------------------ ------- ----------
EMP TABLE
TONY_1 TABLE
TONY_4 TABLE
TONY_EMP TABLE
SQL> select * from emp where rownum < 3;
ID
----------
1
2
SQL> select * from tony_emp where rownum < 3;
ID
----------
1
2
SQL> spool off
Answer Question
2 Users have rated as useful.
Dear Maria...
I traied with the DBA previlage but... again the same prob.. proc created but table is not thea... ok I
tried u r proc and mail back to you...
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Its depend upon the query. If the two queries are firing on the table it is not possible. If the queries are
firing on different different tables then it is possible.
Thanks & Regards
Madhu D.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi Suri !!
Forward Declaration means.. If you are defining a package body having two procedures , If u
want to use second procedure in the defination of first procedure.. You have to declare the second
package with its arguments(if have) before using in the defination of first procedure.. its labled as
forward declaration..
Thanks&Regds
Ramki,Tata Cosnultacny Services,
Deccan Park,HYD,India
Answer Question
2 Users have rated as useful.
One must declare an identifier before referencing it. Once it is declared it can be referred even before
defining it in the PL/SQL. This rule applies to function and procedures also
Answer Question
PL/SQL does not allow forward references. You must declare an identifier before using it.
Therefore, a subprogram must be declared before calling it. You can use forward declarations to
do the following:
• Define subprograms in logical or alphabetical order
• Define mutually recursive subprograms
• Group subprograms in a package
Mutually recursive programs are programs that call each other directly or indirectly.
Answer Question
Regards,
Siva.P
Birlasoft
Bangalore
Answer Question
END pkg_CBRef_Seq;
/
PROCEDURE sp_CBRCreateDropSeq_scd
( p_cod_CountryCode IN country.country_code%TYPE,
p_cod_LegVeh IN leg_veh.leg_veh%TYPE)
AS
BEGIN
sp_CBRCreateDropSeq_cd(p_cod_CountryCode,cur_LegVeh);
/*procedure is called here only because it is forward declared (not defined till now)*/
END sp_CBRCreateDropSeq_scd;
For example, if program A calls program B and program B calls program A, PL/SQL supports mutual
recursion, where two or more programs directly or indirectly call each other.
Package created.
FUNCTION my_func
RETURN NUMBER
IS
BEGIN
RETURN my_func2; -- Legal call
END my_func;
FUNCTION my_func2
RETURN NUMBER
IS
BEGIN
RETURN 0;
END my_func2;
END my_pkg;
/
Package body created.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
ROWID - Hexa decimal number each and every row having unique.Used in searching
ROWNUM - It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are
NEXTVAL,CURRVAL Of sequence are some exampls
[email protected]
Answer Question
3 Users have rated as useful.
psoducolumn in the sence which is not created by the user explicitly but user can use those things
explicityly.
examples
rowid,rowno,currval,nextval,sysdate,uid,level.
RowID: While storing in the database oracle generates one id for each row.
you can call based upon the rowid .ex: select * from emp where rowid=....
RowNo : This no is also generated by oracle itself. but you cant call based upon this one in select clause
Answer Question
Even ROWID is also not permanent for life time.Because If one exports and imports the table data then
ROWID changes.
Answer Question
1 User has rated as useful.
For each row returned by the query a Rownum, pseudocolumn is returned in which order oracle selects
the rows from the table. Using rownum one can even limit the number of rows selected from the table.
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can
select from pseudocolumns, but you cannot insert, update, or delete their values. This section
describes these pseudocolumns:
- CURRVAL and NEXTVAL
- LEVEL
- ROWID
- ROWNUM
Answer Question
3 Users have rated as useful.
Row NUM: A sequence number used to retrieve rows from the table.
Some other Pseudo columns are - Level, Rowscn, UID, User, Sysdate.
Answer Question
If using ORDER BY with ROWNUM then the rows will be reordered by the ORDER BY clause, means the
sequence of rows will be different. it is better to use ROW_NUMBER() analytic unction.
Example:
SELECT * FROM emp WHERE ROWNUM < 11 ORDER BY ename;
Fix:
SELECT * FROM (SELECT * FROM emp ORDER BY empno) WHERE ROWNUM < 11;
Answer Question
Here I am providing all the psudo columns of Oracle ROWNUM, ROWID,NEXTVAL, CURRVAL, SYSDATE,
USER, LEVEL
Answer Question
rownum is also octal decimal number but it is for only specific time span it will arise after completed a
task.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi Rajan,
I do not know what do you mean by application funciton/procedure. In Oracle terms, a PL/SQL block
which is stored ( meaning, you define once; and you can call that procedure or function from other part
of application; if you grant permission to others, they will also be able to acces that procedure or function
) in the database. Here youn can ask the question "What are the other type of procedure or functions
available in Oracle?"...... The answer is, you can have a procedure or function defined within a pl/sfql
block. This enables you to call that pro/function from that pl/sql block only. Moreover, you can define
pro/function in packages aswell.
Are you clear now....? if not, do not hesitae to ask me...
Regards,
[email protected]
Answer Question
hi friend,
i think that there is no difference between stored procedure and applicaton procedure.both r stoed in the
data base only they can call any where required what do say plz give me replaye by seeing this
Answer Question
Stored procedures or functions: Named PL/SQL blocks stored in the Oracle server; can accept parameters
and can be invoked repeatedly by name and are available in Oracle server.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
advantage :
In pl/sql if you want perform some actions more than one records you should user these cursors only.
bye using these cursors you process the query records. you can easily move the records and you can exit
from procedure when you required by using cursor attributes.
disadvantage:
using implicit/explicit cursors are depended by sutiation. if the result set is les than 50 or 100 records it is
better to go for implicit cursors. if the result set is large then you should use exlicit cursors. other wise it
will put burdon on cpu.
Answer Question
IMPLICIT CURSORS are used primarily when returning a single row of data.
With Implicit cursors, the declaration, open, fetch and close functions are done
automatically.
Answer Question
The main disadvantage of cursors is that it process records sequentially. It increases number of context
switches between sql and pl/sql. It hampers the performance. We may overcome this problem by using
collections.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,
U define a variable in the SQL Prompt as ref cursor ,Before that u have to write a procedure with a sys
ref cursor as a inout parameter.Then execute the procedure by passing the variable defined in the SQL
prompt and print the variable, It will display the records.
Mano
Answer Question
Hi,
You could do the same as given under below for emp table.....
CREATE OR REPLACE procedure proc
as
begin
declare
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor c_emp is
select empno,ename from emp;
begin
open c_emp;
loop
fetch c_emp into v_empno , v_ename;
dbms_output.put_line(v_empno||' '|| v_ename);
exit when c_emp%notfound;
end loop;
close c_emp;
end;
end proc;
/
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
All Oracle segments have an upper boundary containing the data within the segment. This upper
boundary is called the "High Water Mark" or HWM", which means table cannot contain data beyond the
HWM
Answer Question
Just to add more when Truncate command is issued it reduces the High Water Mark - the same can be
simulated in case of delete also using
alter table move;
Some time select query takes a lot of time but can't find any data - this is also because of HWM without
any data created by a delete statement
Answer Question
Just to correct my friend's answer to some extend, HWM is basically the max space a particular table as
occupied till that pt. that doesn't mean that one cannot insert records more than a HWM. Once HWM is
crossed a new HWM is set for a table.
Answer Question
Within a segment, the high water mark indicates the amount of used space, or space that had been
formatted to receive data.You cannot release space below the high water mark (even if there is no data
in the space you want to deallocate). However, if the segment is completely empty, you can release
space using the TRUNCATE ... DROP STORAGE statement.
Answer Question
1 User has rated as useful.
Sudhir Sorout
what is pragma?
can any one give me the example of autonomous Transaction ?
can we change the order of procedure parameter while calling procedure?
Asked by: Interview Candidate | Asked on: Jun 11th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
ABOUT PRAGMApragma'S are private transactions , which does not affect anyother transaction. consider
procedure1 is calling procedure2, after finishing a transaction in the second procedure if a error occurs in
the procedure1 then all the transactions will be rolled back ( even tat happend in the procedure2) , if
pragma_autonomous transaction is used in the second procedure ...tat transaction can be
savedhttp://www.psoug.org/reference/autonomous_tx.htmlI HOPE TAT LINK WILL GIVE U A MUCH
BETTER PICTUREREGARDSd.r. KHARTHY
Answer Question
Answer Question
prgma is a compiler directive, it takes the oracle description error name from database for oracle error
code.
Example of autonous transaction:
Autonomous Transaction is a feature of oracle 8i which maintains the state of its
transactions and save it , to affect with the commit or rollback of the surrounding
transactions.
no rows selected
X
----------
1
With PRAGMA AUTONOMOUS_TRANSACTION , the transaction state maintained
independently . Commit/Rollback of nested transaction will no effect the other
transaction. It is advisable to increase the value of TRANSACTIONS parameter in
the INIT parameter file to allow for the extra concurrent transaction .
Answer Question
2 Users have rated as useful.
A pragma is compiler directive. Pragmas are processed at compile time, not at run time. They pass
information to the compiler.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Yes we write commit on trriger but only in autonomous transaction only. But is hardy recomended
Answer Question
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
i PLS_INTEGER;
BEGIN
SELECT COUNT(*)
INTO i
FROM t1;
INSERT INTO t2
VALUES
(i);
COMMIT;
END;
/
Answer Question
1 User has rated as useful.
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
i PLS_INTEGER;
BEGIN
SELECT COUNT(*)
INTO i
FROM t1;
INSERT INTO t2
VALUES
(i);
COMMIT;
END;
/
Previous
Next
Last
Return back to PL/SQL
Answer Question
TRUNCATE
It's a DDL command and delete the complate table data and no rollback possible.It also resets the HIGH
WATERMARK which will imporve subsequent query performance.
DELETE
This is DML statement and require commit to make changes permanant.Can be used to delete selective
rows from table.Does not reset the High Watermark of the table.
Answer Question
1 User has rated as useful.
Nagabhushan S N is right.
Answer Question
TRUNCATE
It is possible to Delete data permanantly from the table without commit.
After deletion don't have rollback option.
DELETE
Require commit to make changes permanantly after delete command.
and also u can select particular row to delete with where conditions.
here after deletion have rollback option
Answer Question
DML Operation.
No Auto Commit.
Truncate
DDL Operation
Auto Commit
Answer Question
2. Delete command deletes records one by one where as truncte removes all the records at a time.
3. Truncate does not allow conditional remove of records where as delete allows conditional remove of
records
4.Trigger fires on delete statement where as trigger do not fires on truncate statement.
Answer Question
1 User has rated as useful.
1) TRUNCATE fires 2 COMMIT before firing and after deleting the rows. The COMMIT fired before,
commits all the open uncommitted transactions.
2) TRUNCATE does not write into redo/undo logs which makes it faster than DELETE.
Correct me if I am wrong.
Cajie
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
When a trigger tries to access its own table, from which its fired, then the trigger is said to be mutating
and table is mutating table.
Answer Question
A table is said to be a Mutating table under the following three circumstances1) When u try to do delete,
update, insert into a table through a trigger and at the same time u r trying to select the same table.2)
The same applies for a view3) Apart from that, if u r deleting (delete cascade),update,insert on the
parent table and doing a select in the child tableAll these happen only in a row level trigger
Answer Question
2 Users have rated as useful.
A mutating table is a table that is currently being modified by an UPDATE, DELETE, or INSERT statement.
A table is not considered mutating for STATEMENT triggers. The triggered table itself is a mutating table,
as well as any table referencing it with the FOREIGN KEY constraint. This restriction prevents a row
trigger from seeing an inconsistent set of data.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Showing Answers 1 - 15 of 15 Answers
Srinivas
Answered On : Jun 2nd, 2006
What is the Data Type of NULL?
In Tech Speack, NULL is a age old concept of nothing. This is not true in case of oracle. Oracle treats
NULL as character value of length of 0.
So, the default data type of NULL is a character data type and to prove it, we create a view on a null
column with an alias a, and then describe it to see the datatype and length of the string. Here is the
code.....
describe myview;
The describe command shows that the column a has a data type of a varchar2(0).
So the Answer is : Character Type
Answer Question
2 Users have rated as useful.
Adding to Prev comments Also Null is and undefined Value its not = 0 ' ' (Space) , also if Value of null
may not be equal to Null (null!= null)(its an unknow value or not defined value.
Answer Question
Data type of NULL is any scalar variable i.e varchar2, char, number, date etc..
Answer Question
NULL value is accepted by Fields that are Number Datatype also. So how can it be varchar. As varchar
values can not be inserted in Field with Datatype as Number.
Answer Question
A null value means the value is unav ailable, unassigned, unknown, or inapplicable. Therefore, you
cannot test with = because a null cannot be equal or unequal to any value.
Answer Question
Character (Char)
Answer Question
How can I speed up the execution of query when number of rows in the tables
increased
Asked by: Interview Candidate | Asked on: May 30th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,
By tuning the query we can increase the execution speed with following TUNING TOOLS
MONITOR
SQL_TRACE and TKPROF
EXPLAIN PLAN
ORADBX
ANALYZE
-Thanks Alot.
Answer Question
Standard practice is -
1. Indexed the columns (Primary key)
2. Use the indexed / Primary key columns in the where clause
3. check the explain paln for the query and avoid for the nested loops / full table scan (depending on the
size of data retrieved and / or master table with few rows)
Answer Question
1 User has rated as useful.
HI
YOU CAN SPEED UP THE QUERY BY USING THE ROWID IN THE SELECT STATEMENT.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Autonomous transaction is the transaction which acts independantly from the calling part and could
commit the process done.
example using prgma autonomous incase of mutation problem happens in a trigger.
Answer Question
2 Procedure InsertInTest_Table_B
3 is
4 BEGIN
6 Commit;
7 END ;
8 BEGIN
10 InsertInTest_Table_B;
11 Rollback;
12 END;
13 /
----------
123
----------
2 Procedure InsertInTest_Table_B
3 is
4 PRAGMA AUTONOMOUS_TRANSACTION;
5 BEGIN
7 Commit;
8 END ;
9 BEGIN
11 InsertInTest_Table_B;
12 Rollback;
13 END;
14 /
no rows selected
----------
You want when ever update statement is fired on emp table. You want a entry should be made in
logfile that emptable is attempted to update no matter updation was successful or not
DECLARE
RMSG VARCHAR2(50) ;
PRAGAMA AUTONOMOUS_TRANSACTION;
BEGIN
SELECT ' EMP TABLE IS UPDATED FROM TERMINAL : '||USERENV('TERMINAL') INTO RMSG
FROM DUAL;
COMMIT;
END;
/
now if user issues
ROLLBACK;
This query will not effect emp table but "emplog" will have a entry
Answer Question
A autonomous transaction starts with the first sql statement of the pl/sql block and ends with a commit.
It starts within the context of an another transaction called parent transaction and independent of it
(parent transaction).To make a transaction autonomous u have to declare PRAGMA
AUTONOMOUS_TRANSACTION at the beginning.
The main adv. of using PRAGMA AUTONOMOUS_TRANSATION is that weather the transaction made by
the parent may be rolled back due to some error, the autonomous transaction has no effect on it.
Suppose if there is any error in autonomous transaction … then >>>> what happen? ? ? don’t
worry***** It will save all the transactions just before the error occurred. Only the last transaction that
has error will be rolled back only if there is no error handler.
Answer Question
An autonomous transaction can be committed or rolled back regardless of the state of the parent
transaction.
What is the difference between In, Out, InOut Parameters. Can we pass value or
reference or both to the In Out Parameter.
Asked by: sbagai2001 | Member Since May-2006 | Asked on: May 26th, 2006
View all questions by sbagai2001 View all answers by sbagai2001
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Eg for in out parameterBellow the parameter having x (eg x_return_status)as suffix is OUT,p (eg
p_calling_fn)as suffix is IN and px (px_trans_rec)as suffix is INOUT.Initializing In parameter is mandatory
to get desired output,OUT will be the result of procedure execution and INOUT will store result processed
by the procedure.Initialize fl_chr_validation, l_num_messg_count,l_chr_messg,l_chr_trans,l_chr_disttrans
proc1( p_validation_level => l_chr_validation , x_return_status => l_chr_return_status , x_msg_count
=> l_num_messg_count , x_msg_data => l_chr_messg , p_calling_fn => NULL , px_trans_rec =>
l_chr_trans , px_dist_trans_rec => l_chr_disttrans);NOTE:- for better analysis/execution Always initkialize
all the parameter IN and OUT.
Answer Question
hi friends,
To make it simple, keep in mind,
IN : It is a CONSTANT in the sub-program and u can not modify its value in sub- program. if its value
is modified in the sub-program then it will give a error.
OUT: the out parameter will always have a NULL value during the begining of the sub-program, we can
modify its value in the sub-program and then this modified value can be sent to the calling program.
Suppose from calling evironment u are sending a variable which has some value to the sub-program, but
if that corresponding variable is mrked as OUT in the sub-program, then in the sub-program that value
will be replaced with NULL, and then the operation in the sub-program will be done.
NOTE: this behaviour can be changed using the NOCOPY option, but remmeber the restriction imposed
on NOPCOY.
IN-OUT: well this is the variable, where u can read the variable and write the variable.
And one more thing to note is that, for OUT and IN-OUT the variables will be passed by value. if
NOCOPY option is not used,
but the restriction with the NOCOPY is that its a hint to the compiler, and not necessary that the
compiler will be using it, so be careful while usin the NOCOPY option.
Answer Question
OUT-- value is returned back from the program to the caller.Must be a variable.
IN OUT-- Its combination of IN and OUT as name suggests. It acts like a varible ie value can be used in
the program and than can be returned back to the caller from the program
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,OUT parameter will be useful for returning the value from subprogram, value can be assigned only
once and this variable cannot be assigned to another variable.IN OUT parameter will be used to pass the
value to subprogram and as well as it can be used to return the value to caller of subprogram. It acts as
explicitly declared variable. Therefore it can be assigned value and its value can be assigned to another
variable.So IN OUT will be useful than OUT parameter.
Answer Question
1) IN OUT and OUT selection criteria depends upon the program need.if u want to retain the value that is
being passed then use seperate (IN and OUT)otherwise u can go for IN OUT.2)If nothing is assigned to a
out parameter in a procedure then NULL will be returned for that parameter.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi,OUT parameter will be useful for returning the value from subprogram, value can be assigned only
once and this variable cannot be assigned to another variable.IN OUT parameter will be used to pass the
value to subprogram and as well as it can be used to return the value to caller of subprogram. It acts as
explicitly declared variable. Therefore it can be assigned value and its value can be assigned to another
variable.So IN OUT will be useful than OUT parameter.
Answer Question
1) IN OUT and OUT selection criteria depends upon the program need.if u want to retain the value that is
being passed then use seperate (IN and OUT)otherwise u can go for IN OUT.2)If nothing is assigned to a
out parameter in a procedure then NULL will be returned for that parameter.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Answer Question
no comments
Answer Question
2. Statement
Rollback the current (ODBC) statement on errors (in case of 8.0 or later
version servers). The driver calls a SAVEPOINT command just before starting
each (ODBC) statement and automatically ROLLBACK to the savepoint on errors
or RELEASE it on success. If you expect Oracle-like automatic per statement
rollback, please use this level.
3. User Level
You can(have to) call some SAVEPOINT commands and rollback to a savepoint
on errors by yourself. Please note you have to rollback the current
transcation or ROLLBACK to a savepoint on errors (by yourself) to continue
the application
Answer Question
3 Users have rated as useful.
Dear Kamini,
May I know what do you mean by PG
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
pl/sql table is temparary table which is used to store records temrparaily in PL/SQL Block, whenever block
completes execution, table is also finished.
Answer Question
Cursor is a pointer to a memory location, where all the rows have been retrieved
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
According to O Reilly Book , the main difference between Index-By Table(pl-Sql Table) , Varray and
nested tables are -
Usable as column No Yes; data stored "out Yes; data stored "in
datatype in a table? of line" (in separate line" (in same table)
table)
Can assign value to Yes No; may need to No; may need to
any element at any EXTEND first EXTEND first, and
time? cannot EXTEND
past upper bound
Means of extending Assign value to Use built-in EXTEND EXTEND (or TRIM),
element with a new procedure (or TRIM to but only up to
subscript condense), with no declared maximum
predefined maximum size
Varry and Nestead table both are belongs to CollectionsThe Main difference is Varray has Upper bound,
where as Nestead table doesn't. It's size is unconstrained like any other database tableNestead table can
be stored in DatabaseSyntax of Nestead TableTYPE nes_tabtype IS TABLE OF emp.empno%type;nes_tab
nes_tabtype;Syntax of VarryTYPE List_ints_t IS VARRAY(8) OF NUMBER(2);aList
List_ints_t:=List_ints_t(2,3,5,1,5,4);
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The main difference between procedure and function,function should return a value.procedure need not
Answer Question
1 User has rated as useful.
Ref cursor return type can be used when it's required that a procedure / function need to return set of
records.
Answer Question
Tuning can be taken care by using the Correct Index on the table.We should not use Not equal to,
Distinct on the Indexed columns.
Answer Question
1. Always use the where clause in your select statement to narrow the number of rows
returned.
If we dont use a where clause, the Oracle performs a full table scan on our table and
returns all of the rows.
2. Use EXISTS clause instead of IN clause as it is more efficient than IN and performs
faster.
Ex:
Replace
SELECT * FROM DEPT WHERE DEPTNO IN
(SELECT DEPTNO FROM EMP E)
With
SELECT * FROM DEPT D WHERE EXISTS
(SELECT 1 FROM EMP E WHERE D.DEPTNO = E.DEPTNO)
Note: IN checks all rows. Only use IN if the table in the sub-query is extremely
small.
3. When you have a choice of using the IN or the BETWEEN clauses in your SQL, use
the BETWEEN clause as it is much more efficient than IN.
Depending on the range of numbers in a BETWEEN, the optimizer will choose to do a
full table scan or use the index.
4. Avoid WHERE clauses that are non-sargable. Non-sargable search arguments in the
WHERE clause, such as "IS NULL", "OR", "<>", "!=", "!>", "!<", "NOT", "NOT
EXISTS", "NOT IN", "NOT LIKE", and "LIKE %500" can prevent the query optimizer
from using an index to perform a search. In addition, expressions that include a
function on a column, or expressions that have the same column on both sides of the
operator, are not sargable.
5. Use equijoins. It is better if you use with indexed column joins. For maximum
performance when joining two or more tables, the indexes on the columns to be
joined should have the same data type.
6. Avoid a full-table scan if it is more efficient to get the required rows through an
index. It decides full table scan if it has to read more than 5% of the table data (for
large tables).
7. Avoid using an index that fetches 10,000 rows from the driving table if you could
instead use another index that fetches 100 rows and choose selective indexes.
8. Indexes can't be used when Oracle is forced to perform implicit datatype
conversion.
9. Choose the join order so you will join fewer rows to tables later in the join order.
use smaller table as driving table
have first join discard most rows
10. Set up the driving table to be the one containing the filter condition that eliminates
the highest percentage of the table.
11. In a where clause (or having clause), constants or bind variables should always be
on the right hand side of the operator.
12. Do not use SQL functions in predicate clauses or WHERE clauses or on indexed
columns, (e.g. concatenation, substr, decode, rtrim, ltrim etc.) as this prevents the
use of the index. Use function based indexes where possible
13. If you want the index used, dont perform an operation on the field.
Replace
SELECT * FROM EMPLOYEE WHERE SALARY +1000 = :NEWSALARY
With
SELECT * FROM EMPLOYEE WHERE SALARY = :NEWSALARY 1000
14. All SQL statements will be in mixed lower and lower case. All reserve words will be
capitalized and all user-supplied objects will be lower case. (Standard)
16. Try joins rather than sub-queries which result in implicit joins
Replace
SELECT * FROM A WHERE A.CITY IN (SELECT B.CITY FROM B)
With
SELECT A.* FROM A, B WHERE A.CITY = B.CITY
17. Replace Outer Join with Union if both join columns have a unique index:
Replace
SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE (+)
With
SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE
UNION
SELECT NULL, B.CITY FROM B WHERE NOT EXISTS
(SELECT 'X' FROM A.STATE=B.STATE)
18. Use bind variables in queries passed from the application (PL/SQL) so that the same
query can be reused. This avoids parsing.
19. Use Parallel Query and Parallel DML if your system has more than 1 CPU.
20. Match SQL where possible. Applications should use the same SQL statements
wherever possible to take advantage of Oracle's Shared SQL Area. The SQL must
match exactly to take advantage of this.
21. No matter how many indexes are created, how much optimization is done to queries
or how many caches and buffers are tweaked and tuned if the design of a database
is faulty, the performance of the overall system suffers. A good application starts
with a good design.
SELECT DISTINCT
SELECT UNIQUE
SELECT ....ORDER BY...
SELECT....GROUP BY...
CREATE INDEX
CREATE TABLE.... AS SELECT with primary key specification
Use of INTERSECT, MINUS, and UNION set operators
Unindexed table joins
Some correlated sub-queries
Answer Question
2 Users have rated as useful.
Ref cursor is used to declare a pointer variable. When you return a ref cursor, you are returning a pointer
variable.
Answer Question
If you want to take care of performance tuning you need to take care of sub-queries as they takes a lot
of time to executing in side the pl-sql blocks.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Source code: The code say a PLSQL block that the user types for the exectionP-Code: The source code
after -Syntax check, Parse tree generation, Symantic check, and further execution of the parse
tree..giving the final P-code ready for data fetch or manipulation ...
Answer Question
2 Users have rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
User_tables data dictionary contains all the tables created by the users under that schema.
whereas All_tables stores all the tables created in different schema. If any user id have the Grants for
access table of diff. schema then he can see that table through this dictionary.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
hi,1. Security reasons we can use view2. If there is a more transaction in a base table we better chose
materialised view for performance 3. Depend upon the situation where we need to refresh the data in
specific time interval.
Answer Question
Hi All,
Tables we used for entity information physically in our DB.
View is a virtual representation of table data, for security and hiding the table column infor. we
used normally view. we uses for Report & MIS purposes for showing the data from more than two table.
Materalized view is used for remote data access and suitable for transaction related data storage in
distributed environment. It stores the data phyisically comparision to normal view. It can refreshes the
remote data auto. and forcefully/manually.
--if the refresh mode is Force
dbms_mview.refresh('Ashok_mview')
Answer Question
Table is the basic entity in any RDBMS , so for storing data you need table .
for view - if you have complex query from which you want to extract data again and again , moreover it
is a standard data which is required by many other user also for REPORTS generation then create view .
Avoid to insert / update / delete through view unless it is essential. keep view as read only (FOR
SHOWING REPORTS)
for materialized view - this view ia mainly used in datawarehousing . if you have two databases and you
want a view in both databases , remember in datawarehousing we deal in GB or TB datasize . So create
a summary table in a database and make the replica(materialized view) in other database.
when to create materialized view-
[1] if data is in bulk and you need same data in more than one database then create summary table at
one database and replica in other databases
[2] if you have summary columns in projection list of query.
main advatages of materialized view over simple view are -
[1] it save data in database whether simple view's definition is saved in database
[2] can create parition or index on materialize view to enhance the performance of view , but cannot on
simple view.
Answer Question
4 Users have rated as useful.
View: If a query is being used again and again then its better to create a view with that query. The query
gets stored in database as an object.
Materialized view: When you want you replicate the main data to multiple sites to reduce the load on
main server materialized views are used. Materialized view is a way of reducing load on main server and
ease of access to local replicated subset of actual data.
Answer Question
We use view to be confidential about the data and to avoid the complexity of a query. But Mviews are
used for performance problem, we use mviews for faster execution of a query. But we need to do regular
refresh for mviews.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
They are similar to a normal curson but they can have different select stmts at run time.
Answer Question
cursor is a memeory area where Oracle process SQL statment , whele ref cursor is a pointer to point
cursor area( memory location), So ref cursor holds location of cursor.
Answer Question
ref cursor is a simple cursor but it is a datatype that allow developers to declare cursor variable
ref cursor has 2 types:-
strong ref cursor where we mention the return type with rowtype.
weak cursor where we don't mention return type.the advantage of this is that we can use weak cursor
with any query.it is not rowtype bounded.
for ex:-strong ref cursor
type curvar_type is ref cursor return emp%rowtype;
weak cursor:-
type curvar_type is ref cursor is
Answer Question
2 Users have rated as useful.
Like a cursor, a cursor variable points to the current row in the result set of a multirow query. However,
cursors differ from cursor variables the way constants differ from variables. A cursor is static, but a cursor
variable is dynamic because it is not tied to a specific query. You can open a cursor variable for any type-
compatible query. This gives you more flexibility.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
REF cursors are different than your typical, standard cursors. With standard cursors, you know the
cursor's query ahead of time. With REF cursors, you do not have to know the query ahead of time. With
REF Cursors, you can build the cursor on the fly
Answer Question
1 User has rated as useful.
Can e truncate some of the rows from the table instead of truncating the full table.
Asked by: Interview Candidate | Asked on: Feb 9th, 2006
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
No , it is not possible. Truncate is a DDL Command and we can not where clause in Truncate.
Answer Question
2 Users have rated as useful.
You can truncate few rows from a table if the table is partitioned. You can truncate a single partition and
keep remaining.
Answer Question
2 Users have rated as useful.
We cannot
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Tune your queries .. like use <= and >= instead of between in case of range specification.
Answer Question
Also the order in which the conditions are given in the 'WHERE' cluase are very important while
performing a 'Select' query. The Performance Difference is unnoticed ifother wise the query
is run on a Massive Database.
For example for a select statement,
SELECT Emp_id FROM Emp_table WHERE Last_Name = 'Smith' AND Middle_Initial =
'K' AND Gender = 'Female';
The look up for matches in the table is performed by taking the conditions in the WHERE cluase
in the reverse order i.e., first all the rows that match the criteria Gender = 'Female' are returned
and in these returned rows, the conditon Last_Name = 'Smith' is looked up.
There fore, the order of the conditions in the WHERE clause must be in such a way that the last
condition gives minimum collection of potential match rows and the next condition must pass on
even little and so on. So, if we fine tune the above query, it should look like,
SELECT Emp_id FROM Emp_table WHERE Gender = 'Female' AND Middle_Initial =
'K' AND Last_Name = 'Smith' ; as Last_Name = 'Smith' would return far more less number of
rows than Gender = 'Female' as in the former Select case.
Answer Question
1 User has rated as useful.
Hi Meenakshi,
It seems that I can get some more detail about TUNING. If I need to tune my query, what are the steps
that I need to take....I know nothing about tuning....If you find time, pls give me some idea...
Regards,
[email protected]
Answer Question
Performance tuning can be improved by using FOR ALL and BULK COLLECT clauses in place of FOR LOOP
and CURSORS which makes the application faster and better.
What happens when a package is initialized ?
Asked by: Shweta_faqs | Member Since Oct-2005 | Asked on: Jan 31st, 2006
View all questions by Shweta_faqs View all answers by Shweta_faqs
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
when a package is initialised that is called for the first time the entire package is loaded into SGA and any
variable declared in the package is initialises.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Showing Answers 1 - 10 of 10 Answers
gayu_rec
Answered On : Feb 8th, 2006
View all answers by gayu_rec
(1).Only in parameters are allowed.No inout & out parameters are allowed.
(2).A DML statement containing a function cannot perform another DML operation on the same table.
Answer Question
We can use IN and IN OUT parameters with function, in Oracle 9i ver. 9.2. See below,
Restrictions of Functions:
1: It has to return a value.
2:Cannot return multiple values.
Answer Question
note:we can return more then one value using INOUT parameters.
Answer Question
DECLARE
A1 NUMBER(3) := 10;
B1 NUMBER(3) := 20;
C1 NUMBER(3) := 30;
D1 NUMBER(3) := 40;
BEGIN
D1 := TEST_FUNC(A1,B1,C1);
DBMS_OUTPUT.PUT_LINE(A1 || ' ' || B1 || ' ' || C1 || ' ' || D1);
END;
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The assigning of values to PL/SQL variables in SQL statements is called binding. PL/SQL binding
operations fall into three categories:
in-bind
out-bind
define
A DML statement can transfer all the elements of a collection in a single operation, a process known as
bulk binding. If the collection has 20 elements, bulk binding lets you perform the equivalent of 20
SELECT, INSERT, UPDATE, or DELETE statements using a single operation. This technique improves
performance by minimizing the number of context switches between the PL/SQL and SQL engines. With
bulk binds, entire collections, not just individual elements, are passed back and forth.
Answer Question
1 User has rated as useful.
How a database language implements binding affects runtime efficiency and flexibility. Binding at compile
time, called static or early binding, increases efficiency because the definitions of database objects are
looked up then, not at run time. On the other hand, binding at run time, called dynamic or late binding,
increases flexibility because the definitions of database objects can remain unknown until then.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
1) A function will return a value, adding to that , it is possible to use a function in SQL statements,
whereas procedures cannot be used.2)No, functions cannot retrun more than one value, instead one can
get this done in other way round by using OUT parameters for a function.3)To perform validations and
transactions on database tables.4)Memory usage is more.5)The variable defined inside Package
Specification are treated as Global variables, which can be referred externally.
Answer Question
3 Users have rated as useful.
Hi,
function can return more than one value - one by return staement and others by OUT parameters.
Answer Question
Both functions and procedures are using to do a special task or action, In functions it is must to return a
single value, where as in procedures its not compulsory, In functions with the help of OUT parameter we
can pass multiple outputs.
The functions can be used in DML statements , but it should satiesfy the function purity level. but
procedures cant use in DML statements.
Answer Question
You can call functions which returned one value from SQL where as procedures you can't
Answer Question
Hi,
The functions are used where we can't used the procedure.i.e we can use a function the in select
statments,in the where clause of delete/update statments.But the procedure can't used like that.
It is true that function can return only one value, but a function can be used to return more than one
value,by using out parameters and also by using ref cursors.
There is no harm in using the out parameter,when functins are used in the DML statements we can't
used the out parameter(as per rules).
Answer Question
Hii
A function can return more than one value. It can be done by using out parameters with the variables,
datatype and size, and calling them in the return clause.
Hope this will help you.
Bye.
Answer Question
functions can return more than a value by returning a ref cursor variable instead of returning a single
value(varchar2 or number). pls notify if this breaks any rule or functionality of oracle ??
Answer Question
Define record type in a package and use this type in your function.
Answer Question
1. Most use of the function is you can call function from your select or any exicuteble statment. You can't
call procedure like function.
2. You can pass any number of values to function and function will retern any number of values but it will
must returnone value.
3. Procedure is used for pass any number of parameter and return any number of values. You can call
procedure from any whare by using call function or execute function.
Answer Question
A function must return a value to the calling environment. Although multiple RETURN
statements are allowed in a function (usually within an IF statement), only one RETURN
statement is executed, because after the value is returned, processing of the block ceases. To
have a function return multiple values is poor programming practice. Also, functions should be
free from side effects, which change the values of variables that are not local to the subprogram.
Procedure is use to perform an action.
Disadvantages of Packages: more memory is required when using packages as the whole
package is loaded into memory as soon as any object in the package is accessed native
compilation can take twice as long as normal compilation.
Global Variables: The variable defined inside Package Specification are treated as Global
variables, that can be referenced outside the package and is visible to external users. Global
package items must be declared in the package specification.
Answer Question
Using Return statement we can return only one value. Even in functions also we may return more than
one value using out parameter. But It is not a good practice to return more than one value using
functions.
Whenever you call a packaged pl/sql construct for the first time, entire package is loaded into memory.
High memory use is the disadvantage.
Variables declared in the package specification part of a package are called global variables.
Answer Question
DECLARE
A1 NUMBER(3) := 10;
B1 NUMBER(3) := 20;
C1 NUMBER(3) := 30;
D1 NUMBER(3) := 40;
BEGIN
D1 := TEST_FUNC(A1,B1,C1);
DBMS_OUTPUT.PUT_LINE(A1 || ' ' || B1 || ' ' || C1 || ' ' || D1);
END;
Answer Question
Eg : Function ( a in number,
b in out number,
c in out number)
Return number;
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Bulk Binds (BULK COLLECT , FORALL ) are a PL/SQL technique where, instead of multiple individual
SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table,
all of the operations are carried out at once, in bulk.
This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine,
then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk
binds with Insert, Update and Delete statements, you enclose the SQL statement within a
PL/SQL FORALL statement.
To do bulk binds with Select statements, you include the Bulk Collect INTO a collection clause in the
SELECT Statement instead of using Simply into .
Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and 10g PL/SQL that can
really make a different to you PL/SQL performance
Answer Question
1 User has rated as useful.
Hi ,
Bulk Binding is used for avoiding the context switching between the sql engine and pl/sql engine. If we
use simple For loop in pl/sql block it will do context switching between sql and pl/sql engine for
each row processing that degrades the performance of pl/sql bloack.
So that for avoiding the context switching betn two engine we user FORALL keyword by using the
collection pl/sql tables for DML. forall is pl/sql keyword.
It will provides good result and performance increase.
Answer Question
1 User has rated as useful.
FOR ALL and BULK COLLECT together are called bulk binding.
In Bulk binding instead of handling records sequentially the operations are carried out at once in bulk.
There by Bulk binding improves performance by minimizing no of context switches between SQL and
PL/SQL.
Can we use commit or rollback command in the exception part of PL/SQL block?
Asked by: Interview Candidate | Asked on: Oct 19th, 2005
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
yes
Answer Question
1 User has rated as useful.
Yes
Answer Question
Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored
procedure/function. The code in this part of the program gets executed like those in the body without
any restriction. You can include any business functionality whenever a condition in main block(body of a
proc/func) fails and requires a follow-thru process to terminate the execution gracefully!
Answer Question
4 Users have rated as useful.
yes we can
Answer Question
COMMIT;
RAISE;
END
Answer Question
Yes
Answer Question
Yes, we can use Commit / Rollback in the Exception part. Declare ---Variable declaration Begin ----
Executable part Exception When others then dbms_output.put_line(sqlerrm); Rollback; END ;
Answer Question
1 User has rated as useful.
Yes We can
Answer Question
Declare
myexception EXCEPTION;
Begin
RAISE myexception;
EXCEPTION
When myexception then
insert into table_name values (......);
COMMIT;
yes we can......
Answer Question
no, we can't use exceptions in ddl statements.normal form sql or sql*plus,without explicitly issuing
commit or rollback statements.
Answer Question
yes.. surely.. you can use any TCL command within the exception block.
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
When Others is always handeled at the very end of all handeled exceptions. In this others should be in
the last means after No_data_Found.
Answer Question
If you are using the exception part in the prg "others" exception should be the last exception that is the
only mistake in the program.
Answer Question
declare
v_empno emp.empno%type;
begin
select empno into v_empno from emp where empno = 10;
exception
when no_data_found then
dbms_output.put_line ( 'ther is no data found ');
when others then
dbms_output.put_line ( 'no data found');
end;
Rgds
Ramya
Answer Question
1 User has rated as useful.
This is due the fact that the 'OTHERS' exception block must be at the last of all the exception in a BEGIN
END block.
In the above code if we put the no_data_found exception in the first place and the others exception after
that then the code will work properly.
Answer Question
1 User has rated as useful.
Error occurs, why because "when others" must and should be placed at last in exception block
Data Consistency => Means that each user sees a consistent view of the data, including visible changes
made by the user's own transactions and transactions of other users.
Asked by: Interview Candidate | Asked on: Sep 5th, 2005
First
Previous
Next
Last
Answer Question
tm1966_muthu
Concurrency
How well can multiple sessions access the same data simultaneously
Consistency
How consistent is the view of the data between and within multiple sessions, transactions or
statements
Answer Question
arvind kumar
types of triggers
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
c) USER_DEPENCENCIES
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
if we declare in package body then what is difference b/w cusrsor..........?how many types of
refcursors..............?whata re the advantages of ref cursors....................?
Answer Question
Ref cursors are used when you want cursor to hold any no. of columns in the row.
If you are not sure about row type at complile time you use ref cursors.
Sys_ref_cursors used when you want cursors to be passed from one procedures to another procedures or
functions.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Overloading procs are 2 or more procs with the same name but different arguments.
Arguments needs to be different by class it self. ie char and Varchar2 are from same class.
Packages -
The main advantages of packages are -
1- Since packages has specification and body separate so, whenever any ddl is run and if any
proc/func(inside pack) is dependent on that, only body gets invalidated and not the spec. So any other
proc/func dependent on package does not gets invalidated.
2- Whenever any func/proc from package is called, whole package is loaded into memory and hence all
objects of pack is availaible in memory which means faster execution if any is called. And since we put all
related proc/func in one package this feature is useful as we may need to run most of the objects.
30 we can declare global variables in the package
Answer Question
Advantages
Modularity
Easier application design
Hiding information
Added functionality
Better performance
Overloading
Answer Question
The main purpose of overloading procedures is that, when a PL SQL block is found to do a same
operation with different inputs, we names them same and feed different parameters
Answer Question
1 User has rated as useful.
Definining two or more procedures with same name is called overloading of procedures. But they must
differ in no or order or datatype family of formal arguments.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
a) CALL direc
a) EXCECUTE from calling environment. Always use a variable to get the return value.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
1) easy maintenance : sub programs are located in one location and hence it is easy to
- modify routines online without interfering with other users
- modify one routine to affect multiple applications
- modify one routine to eliminate duplicate testing
3) improved performance
avoids pl/sql parsing at run time by parsing at compile time
Answer Question
In addition to modularizing application development, stored procedures and functions have the
following benefits:
1) Improved performance
Avoid reparsing for multiple users by exploiting the shared SQL area
Avoid PL/SQL parsing at run time by parsing at compile time
Reduce the number of calls to the database and decrease network traffic by bundling commands
• Easy maintenance
– Modify routines online without interfering with other users
– Modify one routine to affect multiple applications
– Modify one routine to eliminate duplicate testing
• Improved data security and integrity
– Control indirect access to database objects from nonprivileged users with security
privileges
– Ensure that related actions are performed together, or not at all, by funneling activity for
related tables through a single path
• Improved code clarity: By using appropriate identifier names to describe the actions of the routine,
you reduce the need for comments and enhance clarity.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
b) It is similar to any subprogram that accepts parameters and performs an action. It may or may not
return a value. This attribute differentiates it from another subprogram type called FUNCTION.
c) It can be nested
e) This stored procedure can be seen as an object in the User_Objects and is different from the
procedures that are created in packages.
Answer Question
1 User has rated as useful.
Stored procedure is a sub program and stored in memory for repated execution
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database trigger.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
i know that the error no in raise_application_error are non standard but tell me on what basis we are
giving those numbers? is that simply a number or it some implicit meaning ?
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Exception is nothing but Error. In PL/SQL block we handle these errors in Exception block.There are two
types of exceptions: 1> System define exception and 2> User define exception. System define exception
predefine exceptions like 'ZERO_DEVIDE',NO_DATA_FOUND etc.User define exceptions is defined by the
user and raise in the excution block and then call into the exception block.
Answer Question
1 User has rated as useful.
Predefined
Do not declare and allow the Oracle server to raise implicitly
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
ZERO_DIVIDE
INVALID_CURSOR
Non predefined
Declare within the declarative section and allow allow Oracle server
to raise implicitly
o SQLCODE Returns the numeric value for the seeor code
o SQLERRM Returns the message associated with error number
User defined
Declare within the declarative section and raise explicitly.
IF confidition the
RAISE EXCEPTION or RAISE_APPLICATION_ERROR
Answer Question
1 User has rated as useful.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
So, if it is before insert trigger then the trigger will run first before the constriants in the table. if it is after
insert trigger , contraints are checked first and then trigger will run.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
In order to avoid mutation table error we need to have a row level as well as a statment level trigger.
Answer Question
What are two virtual tables available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.For triggers related to
INSERT only NEW.column_name values only available.For triggers related to UPDATE only
OLD.column_name NEW.column_name values only available.For triggers related to DELETE only
OLD.column_name values only available.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
INSERT statement has access only to new values. Old values are NULL for insert statement.
DELETE satement has access only to old values. New values are NULL for delete statement.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
If the trigger is declare as autonomous transaction, then it can have commit or rollback.
Answer Question
2 Procedure InsertInTest_Table_B
3 is
4 BEGIN
6 Commit;
7 END ;
8 BEGIN
10 InsertInTest_Table_B;
11 Rollback;
12 END;
2 Procedure InsertInTest_Table_B
3 is
4 PRAGMA AUTONOMOUS_TRANSACTION;
5 BEGIN
8 END ;
9 BEGIN
11 InsertInTest_Table_B;
12 Rollback;
13 END;
COMMIT, ROLLBACK, and SAVEPOINT statements are not allowed within the trigger body. It is possible
to commit or rollback indirectly by calling a procedure, but it is not recommended because of side effects
to transactions.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Data auditing , Implementing complex business rules, security are main uses of database triggers.
Answer Question
3 Users have rated as useful.
by using trigger we can do the auditing and perform a operation(modifications) on a tables (using dml
operation)
Answer Question
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
"WHERE CURRENT OF" clause is used for updating or deleting rows selected by the cursor with FOR
UPDATE cluase.It explicitily locks the row for updating or deleting.
Answer Question
1 User has rated as useful.
Login to rate this answer.
g_sidhu
Answered On : Jan 31st, 2008
When referencing the current row from an explicit cursor, use the WHERE CURRENT OF
clause. This
allows you to apply updates and deletes to the row currently being addressed, without the need to
explicitly reference the ROWID. You must include the FOR UPDATE clause in the cursor query to
lock the rows first.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
The cursor having query will get closed, because once the for update clause is fired it locks all the rows
which is been modified and once it encounters a commit/rollback it automatically comes out of that
session, and will be processing a fresh loop altogether.
Answer Question
DDL statements cannot be included in the pl/sql block. Hence giving commit is not allowed.
Answer Question
Login to rate this answer.
hanthur
Answered On : Feb 23rd, 2006
View all answers by hanthur
If the data set is too big commiting with-in the cursor loop might lead to the `Snapshot too old Error`.
Answer Question
after the commit statement, the cursor get closed ...as the result no further rows can be fetched even
though there are rows to be fetched.
Answer Question
In this PL/SQL Block the curosrfetch the records in both the variable till the time it get record. After
fetching all the records when the condition %not found is true it execute the commit and save all the
record which is fetched at the time of execution.
Answer Question
Cheers!!
Answer Question
Commit in this context will not do anything except the commiting the changes into database, done using
DML statements. However, if the cursor is created with FOR UPDATE clause, it will raise runtime
exception as commit, in that case, would also release all locks and thus close the cursor implicitly and
user will get ORA-1002 "fetch out of sequence " error as after the loop is executed one time, with the
commit statement, the cursor will be closed and fetch into statement will fail.
Answer Question
1 User has rated as useful.
The log writer makes redo log entries in redo log files after that message comes commit complete.
Also by using commit the changes made by update statement will be seen in database permanently.
Answer Question
The data will be written from redo log buffer into redo log files.
Answer Question
After committing first oracle will commit the transaction into redo log file and then Data file. The data
block will remain into the memory until the logical reads are going on. Oracle use LRU algorithm to
maintain the data block into the memory. Also oracle maintain rollback segment before committing the
data to store original version of data.
What is a cursor for loop ?
Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values
from active set into fields in the record and closeswhen all the records have been processed. eg. FOR
emp_rec IN C1 LOOP salary_total := salary_total +emp_rec sal; END LOOP;
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Cursor for loop implicitly declares a loop index as %rowtype. It uses result of query to determine
dynamically no of times the loop is to be repeated. It performs open, fectch , close operations implicitly.
Answer Question
1 User has rated as useful.
If we use cursor for loop cursor will open the cursor and fetching data and close the cursor automatically.
Answer Question
Cursor for loop is the one by using this we need not to perform open, close, fetch operations of a cursor..
Answer Question
Previous
Next
Last
Return back to PL/SQL
Answer Question
Answer Question
1 User has rated as useful.
%isopen
With %isopen it is possible to test whether a cursor was opened:
%found
%found returns true when the last fetch operation on the cursor fetched a row. If %found is used on a
cursor that is not open (%open returns false), an ORA-01001: invalid cursor is raised. %notfound returns
null is returned:
%notfound
%notfound returns true when the last fetch operation on the cursor did not fetch a row. If %notfound is
used on a cursor that is not open (%open returns false), an ORA-01001: invalid cursor is raised.
%notfound returns null is returned:
%rowcount
%rowcount returns the number of rows that have been fetched so far. So, it increases with each fetch:
%bulk_rowcount
%bulk_rowcount is similar to %rowcount, but is used in bulk collects.
Answer Question
%FOUND - To check wheteher cursor is found or not. Returns true if fetch returns a row otherwise false.
%NOTFOUND - To check whether cursor is not found or not.This works logically opposite to %FOUND.
This is usec to exit a loop when fetch fails to return a row.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
If the cursor is dynamic, it needs to be processed thro open cursor, fetch into, loop and end loop. This is
because such cursors need to be opened into a ref cursor with "open cursor" command.
If the cursor is static, it can be processed thro a cursored for loop or by the method mentioned above.
Cursored for loop takes the pain to open and close the cursor automatically.
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
implicit cursor: implicit cursor is a type of cursor which is automatically maintained by the Oracle server
itself.implicit cursor returns only one row.
Explicit Cursor: Explicit Cursor is defined by the Proframmer,and it has for phases:declare,open,fetch and
close.explicit Cursor returns more than one row.
Answer Question
2.Explicit cursors:- In explicit cursor you can explicitly assign a name to process information stored in
private sql areas. This process involves four steps
I. Declaring a cursor :- Involves assign a name to cursor and associating a query with it..
II. Open the cursor :- Executes the query and identify the result set.
III. Fetch the cursor :- gets the result set and Loops through to process them
IV. Close the cursor :- Releases the cursor
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Cursor is a handler or pointer to Oracle Context Area.Context area is a memory space used for processing
of sql statements.
Answer Question
CURSOR
Whenever a sql statement is issued, at that time oracle server will allocate some memory area to execute
and parse that sql statement. That data area is called as cursor.
IMPLICIT
-----------
(1) Called as SQL.
(2) Never user CURSOR keyword explicitly
(3) Memory allocation and program controll will done automatically
(4) Returns or updates or deletes only one record.
(5) Attributes : SQL%FOUND, SQL%NOTFOUND
EXPLICIT
-----------
(1) called as cursors
(2) Uses CURSOR keyword explicitly
(3) Memory allocation and program control thru the cursor written.
(4) Returns or updates or deletesmultiple records.
(5) Attributes : SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT
Answer Question
3 Users have rated as useful.
Cursor is a handler or a pointer to the context area. throught cursor pl/sql programcan control the
context area and what happens to it as thestatment process.
Most common operation using cursor is to fetch data rows in the active set.
Answer Question
In Pl/Sql block if a query returns more than one row it raises an exception TOO_MANY_ROWS. Using
cursors mechanism we can process multiple rows returned by the query in pl/sql blocks.
Answer Question
2 Users have rated as useful.
First
Previous
Next
Last
A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional array.
Unbounded or Unconstrained
There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table grows
dynamically as you add more rows to the table. The PL/SQL table is, in this way, very different
from an array.
Related to this definition, no rows for PL/SQL tables are allocated for this structure when it is
defined.
Sparse
In a PL/SQL table, a row exists in the table only when a value is assigned to that row. Rows do
not have to be defined sequentially. Instead you can assign a value to any row in the table. So
row 15 could have a value of `Fox' and row 15446 a value of `Red', with no other rows defined in
between.
Homogeneous elements
Because a PL/SQL table can have only a single column, all rows in a PL/SQL table contain
values of the same datatype. It is, therefore, homogeneous.
With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is still,
however, homogeneous. Each row simply contains the same set of columns.
Indexed by integers
PL/SQL tables currently support a single indexing mode: by BINARY_INTEGER. This number
acts as the "primary key" of the PL/SQL table. The range of a BINARY_INTEGER is from -231-1
to 231-1, so you have an awful lot of rows with which to work
kishorebabukm
Pl/SQL tables are the row, column structure as of the table but cannot perform any select query on the
pl/sql tables because the data isfrom fetched only by the indexes like
--- store empno, ename from emp table thru cursor to pl/sql tables.
declare
type ty_plsql is record ( empno number, ename varchar2(50));
ty_plsql1 ty_plsql;
cursor c is select empno,ename from emp;
begin
for i in c loop
ty_plsql(i).empno := i.empno;
ty_plsql(i).ename := i.ename;
end loop;
end;
Answer Question
rkanth18
A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional array.
Unbounded or Unconstrained
There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table grows
dynamically as you add more rows to the table. The PL/SQL table is, in this way, very different
from an array.
Related to this definition, no rows for PL/SQL tables are allocated for this structure when it is
defined.
Sparse
In a PL/SQL table, a row exists in the table only when a value is assigned to that row. Rows do
not have to be defined sequentially. Instead you can assign a value to any row in the table. So
row 15 could have a value of `Fox' and row 15446 a value of `Red', with no other rows defined
in between.
Homogeneous elements
Because a PL/SQL table can have only a single column, all rows in a PL/SQL table contain values
of the same datatype. It is, therefore, homogeneous.
With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is still,
however, homogeneous. Each row simply contains the same set of columns.
Indexed by integers
PL/SQL tables currently support a single indexing mode: by BINARY_INTEGER. This number acts
as the "primary key" of the PL/SQL table. The range of a BINARY_INTEGER is from -231-1 to 231-
1, so you have an awful lot of rows with which to work
Answer Question
rkanth18
Keep the following restrictions in mind when you work with PL/SQL tables:
There is no concept of transaction integrity with PL/SQL tables. You cannot commit information to a
PL/SQL table or roll back changes from the table.
You cannot SELECT from PL/SQL tables. There is no way to perform set-at-a-time processing to retrieve
data from a PL/SQL table. This is a programmatic construct in a programmatic language. Instead you can
use PL/SQL loops to move through the contents of a PL/SQL table, one row at a time.
You cannot issue DML statements (INSERTs, UPDATEs, and DELETEs) against PL/SQL tables (though
PL/SQL Release 2.3 does offer a DELETE operator).
Answer Question
iasritesh
An associative array (or INDEX-BY table) that can be indexed by NUMBER or VARCHAR2. Elements are
retrieved using number or string subscript values. Unlike with data tables, PL/SQL tables are stored in
memory. PL/SQL Tables are sparse and elements are unordered.
Answer Question
babu.sridharan
declare
type ty_plsql is record ( empno number, ename varchar2(50));
TYPE ty_plsql2 is table of ty_plsql;
ty_plsql1 ty_plsql2;
j number;
cursor c is select empno,ename from emp;
begin
ty_plsql1:=ty_plsql2(NULL,NULL);
for i in c loop
j:=1;
ty_plsql1(j).empno := i.empno;
ty_plsql1(j).ename := i.ename;
dbms_output.put_line('Print the value : '||' No '|| ty_plsql1(j).empno ||' Name '|| ty_plsql1(j).ename);
j:=j+1;
end loop;
end;
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
basically the %rowtype is used in case of fetching the values of the cursor irrespective of how many
columns in it and also the data types associated with the tables column.for eg.
declare
cursor c_example is select * from emp;
v_emp emp%rowtype;
begin
for v_emp in c_example loop
statements
......
end loop;
end;
the type record is a object oriented concept related to pl/sql tables, tables with datastructure format etc.
create type ty_name is record ( a number,
b varchar2(10));
this type stores data in a record fashion with 2 columns.
Answer Question
1 User has rated as useful.
%rowtype is an attribute to inherit datatypes of attributes of a table into a RECORD variable. Type record
is a keyword to create record type using either explicitly specifying atrributes or by implecitly inheriting
attributes from a table or a existing cursor.
Answer Question
Login to rate this answer.
nagarajkv
Answered On : May 5th, 2008
View all answers by nagarajkv
TYPE RECORD is a composite datatype. It consits of multiple pieces of information, called fields. TYPE
RECORD fields can be defined by the user. Eg:
DECLARE
TYPE extra_book_info_t
IS RECORD (
title books.title%TYPE,
is_bestseller BOOLEAN
);
first_book extra_book_info_t;
here, 'title' is the data type defined in books table. We can declare a RECORD based on this type.
Where as %ROWTYPE is a direct link to the data type of the table.columns, EG:
DECLARE
bestseller books%ROWTYPE;
The advantage of TYPE RECORDS is you can pass these to Functions or Procedures which can reduce the
parameter size or a repitative work.
What are % TYPE and % ROWTYPE ? What are the advantages of using these
over datatypes?
% TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE
provides the record type that represents a entire row of a table or view or columns selected in the
cursor. The advantages are : I. Need not know about variable's data typeii. If the database definition
of a column in a table changes, the data type of a variable changes accordingly.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
eg:
ename employees.emp_id%type;
here ename is the variable to be declared.
employees is the table name
emp_id is the column for that table.
%type indicates to assign the datatype of emp_id column in employees table for the ename variable.
Answer Question
%type is used to refer the column's datatype where as %rowtype is used to refer the whole record in a
table.
Answer Question
1 User has rated as useful.
EX:
V_EMPNOEMP.EMPNO%Type;
Where as
Ex:
V_EMP EMP.%ROWTYPE.
Answer Question
1 User has rated as useful.
%ROWTYPE can be used to declare the variable having the same no. of variables inside it (ROWTYPE) as
no. of columns there in the table. In this case columns selected with SELECT statement must match with
variables inside the rowtype variable. If not then induvidually refer these variables inside the ROWTYPE
variables
Answer Question
1 User has rated as useful.
declare
var1 production.invoice.itemno%type;
%Rowtype - With %rowtype attribute we can inherit the datatypes entire variable into a record varible
from another record variable or from all attributes of table into currently declared record variable.
eg.
declare
record1 production.invoice%rowtype;
Advantage is u need not to change the pl/sql code even if table attribute changes.
u need not to remember detail datatypes of table while coding pl/sql
Answer Question
1 User has rated as useful.
%TYPE is used to declare a variable with the same type as that of a database table column.%ROWTYPE
is used to declare a record as same type found in database table.These two provides data independence
and allows you to adopt database changes due to new business requirements.You need not know
datatype and size in advance.
Answer Question
1 User has rated as useful.
The benefit of %TYPE and %ROWTYPE is when u are fetching the data from a table in procedure and
after that data type of column or size is changed then no need to modify the procedure.
Answer Question
- It is good practice to use %TYPE and %ROWTYPE instead of defining varible of simple type. In case of
any change in the data type of columns and no need to make any changes to code.
- %ROWTYPE can be used to fetch complete row instead ofdefining varible for each field to hold the data
while processing.
Answer Question
We Can USE These Data Types in Stored Procedures ,function and Packages as IN Parameter.
Answer Question
if using %type and %rowtype , no need to know the the data type of the table column . and once the
development is finished , the type of column is changed it will not effect the coding.
Answer Question
%type is associated with one column .(if we want to declare entire column then we need to declare
%type).
What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural programming
language constructs such as iteration, conditional branching.
Asked by: Interview Candidate | Asked on: Sep 9th, 2004
First
Previous
Next
Last
Return back to PL/SQL
Answer Question
Hi Sir,
1.What is PL/SQL ?
Answer :
PL/SQL is Procedural Language extension to SQL. PL/SQL's language syntax, structure and
datatypes are similar to that of ADA. The language includes object oriented programming techniques
such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-
of-the-art programming to the Oracle database server and a variety of Oracle tools.
Answer Question
New Term - If you have worked with relational databases in the past, you are no doubt familiar with
SQL, which stands for Structured Query Language. SQL itself is a powerful declarative language. It
isdeclarative in the sense that you describe the results that you want but not how they are obtained. This
is good because you can insulate an application from the specifics of how the data is physically stored. A
competent SQL programmer can also push a great deal of processing work back to the server level
through the creative use of SQL.
Answer Question
1 User has rated as useful.
PL SQL is a block structured programming language. It combines data manipulation & data processing
power. It supports all SQL data types. Also has its own data types i,e BOOLEAN,BINARY INTEGER
Answer Question