oracle 10g plsql_1
TRANSCRIPT
-
8/14/2019 Oracle 10g PLSQL_1
1/17
Oracle Concepts
Selvaraj V
Anna University Chennai.
Chennai 25.
-
8/14/2019 Oracle 10g PLSQL_1
2/17
what is the output of this query selet * from employee where 1=2 ?
SQL> select * from job where 1=2;
no rows selected.
what are pl/sql collections?
A collection is an ordered group of elements, all of the same type. It is a general
concept that encompasses lists, arrays, and other familiar datatypes. Each element
has aunique subscript that determines its position in the collection.
PL/SQL offers these collection types:
* Index-by tables,
* Nested tables
* Varrays
How to add Foreign key in a table after the creation of the table?
alter table table2
add (constraint table2_col2_fk foreign key(col2) references
table1(col1);
here col2 is the foreign key of table2 which refer to the col1 of table1 which is h
epimary key of table1
what is the difernece between named and anonymous pl/sql blocks?
Anonymous block those pl/sql blocks which are not stored in your DB as an objects,
whereas named pl/sql blocks are those blocks which are stored in DB as an
objects.Due to storage in DB, these named pl/sql blocks can be called from another
named or anonymous blocks, or from any form also...
the purpose of an anonymous block is to write a one timecode e.g. you can write
statements using SQL PLus editor and accomplish database changes and do stuff
which you can also do by creating a procedure
YOU CAN NOT PASS PARAMETERS IN ANONYMOUS BLOCK WHERE AS YOU CANPASS IT IN NAMED PLSQL BLOCK.
YOU CAN CALL NAMED BLOCK FROM ANY DB(USING DB LINK)
how do you count the duplicate records in a table
select count(0) from tab1 a
-
8/14/2019 Oracle 10g PLSQL_1
3/17
where a.rowid > any (select b.rowid from tab1 b where a.col1 =b.col1);
select col1,count(col1) from tab1 group by col1 having count(col1)>1;
If you want to delete these duplicate entries, use:
delete from tab1 where col1 in (select a.col1 from (select col1,count(col1) from tab1
group by col1 having count(col1)>1) a);
select count(*) from table_name group by column1,column2...
having count(*) > 1
how to get the third quarter of employee details from emp?
select * from job where rownum
-
8/14/2019 Oracle 10g PLSQL_1
4/17
Yes,Store Procedure/Procedure are one and the same.We have to Create Procedure
and Compile it in Data base,once compiled it will be stored and we can use the same
when ever required in various other Procedures.
Procedure Usually used to perform set of actions based on conditions.
what is Complex index. how to create it?
Do you mean Composite Index?
Composite index is the index created on multiple columns of a table. A maximum of
16 columns can be used as a composite index. It can be created at table level only.
Unique, Primary Key and Foreign Key can be composite keys.
Ex:
Create table emp(eno number,
ename varchar(5),
dob date,
sal number,
dno number,
Primary Key(eno, ename) -- Composite Index
);
i want to display 1 to 10 numbers using one select statement.
select level from dual connect by level
-
8/14/2019 Oracle 10g PLSQL_1
5/17
A REF CURSOR is basically a data type. A variable created based on such a data
type is generally called a cursor variable. A cursor variable can be associated with
different queries at run-time. The primary advantage of using cursor variables is
their capability to pass result sets between sub programs (like stored procedures,
functions, packages etc.).
Let us start with a small sub-program as follows:
declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
en emp.ename%type;
begin
open c_emp for select ename from emp;
loop
fetch c_emp into en;
exit when c_emp%notfound;dbms_output.put_line(en);
end loop;
close c_emp;
end;
Ref cursor is a cursor variable which acts as a pointer to the sql memory area.
Ref cursor can be asssociated with multiple sql statements where as a cursor can be
associated with only one sql statement.
Refcursor is dynamic where as cursor is static.
Ref cursors are of two types:
1)strong ref cursor:which retuns value.
2)week ref cursor:which doesn't return value.
What are the type of triggers available in Oracle Reports ?
trere are five types report trigger
1 before parameter form
2 after parameter form
3 before report
4 between pages
5 after report
-
8/14/2019 Oracle 10g PLSQL_1
6/17
Other Triggers :
(1) Validation Triggers
(2) Format Triggers
(3) Action Triggers
There are five types of trigger in Oracle Reports
Before Parameter Form
Fires before the Runtime Parameter Form are displayed. Can access the PL/SQL
global variables, report level columns and manipulate accordingly.
After Parameter Form
Fires after the Runtime Parameter form are displayed. Used to validate theparameter values.
Before Report
Fires before the report is executed but after the queries is parsed and date is
fetched.
Between Pages
Fires before each page of the report are formatted, except the very first page. This
page is used to customize page formatting.
After Report
Fires after the report previewer are exited, or after report output is sent to a
specified destination.
Validation Triggers
Validation Triggers are PL/SQL functions that are executed
when parameter values are specified on the command line and when you accept the
Runtime Parameter Form. (Notice that this means each Validation Trigger may firetwice when you execute the report).
Validation Triggers are also used to validate the Initial Value of the parameter in
the Parameter property sheet.
-
8/14/2019 Oracle 10g PLSQL_1
7/17
Format Triggers
Format Triggers are PL/SQL functions executed before the object is formatted. The
trigger can be used to dynamically change the formatting attributes of the object.
Action Triggers
Action Triggers are PL/SQL procedures executed when a button is selected in the
Previewer.
The trigger can be used to dynamically call another report (drill down) or execute
any other PL/SQL.
Display the number value in Words?
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only.SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
What are cursor attributes?
-%ROWCOUNT
-%NOTFOUND
-%FOUND
-%ISOPEN
-
8/14/2019 Oracle 10g PLSQL_1
8/17
Difference between NO DATA FOUND and %NOTFOUND
NO DATA FOUND is an exception raised only for the SELECT....INTO statements
when the where clause of the query does not match any rows. When the where
clause of the explicit cursor does not match any rows the %NOTFOUND attribute is
set to TRUE instead.
NO_DATA_FOUND is pre defind exception of oracle. when we can't get any data from
the table for any query. In that case we will get error.
%NOT FOUND is one of the attribute of explicit cursor.
when can't get any data from explicit cursor in that case %NOT FOUND will returns
true otherwise it returns false.
What are various privileges that a user can grant to another user?
-SELECT
-CONNECT
-RESOURCES
Difference between procedure and function
Functions are named PL/SQL blocks that return a value and can be called with
arguments procedure a named block that can be called with parameter. A procedure
all is a PL/SQL statement by itself, while a Function call is called as part of an
expression.
Function and Procedure both are PL/SQL blocks, main difference between function
and procedure is
Function has to return some value using return clause whereas procedure may or
may not return any value( no out parameter).
We can use functions in SQL query but can't use procedure.
What is difference between SQL and SQL*PLUS?
SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and
reporting tool. Its a command line tool that allows user to type SQL commands to be
executed directly against an Oracle database. SQL is a language used to query the
relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query
result, Set options, Edit SQL commands and PL/SQL.
SQL * Plus is an environment.
Keywords can be abbreviated.
-
8/14/2019 Oracle 10g PLSQL_1
9/17
SQL is a Query Language.
Keywords cannot be abbreviated.
Differentiate between TRUNCATE and DELETE
TRUNCATE deletes much faster than DELETE
TRUNCATE
DELETE
It is a DDL statement
It is a DML statement
It is a one way trip,cannot ROLLBACK
One can Rollback
Doesn't have selective features (where clause)
HasDoesn't fire database triggers
Does
It requires disabling of referential constraints.
TRUNCATE HAS NO CONDITION CLAUSE. WHERE AS DELETE HAS CONDITION.
What should be the return type for a cursor variable.Can we use a scalar
data type as return type?
The return type for a cursor must be a record type.It can be declared explicitly as a
user-defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSORRETURN students%ROWTYPE
What is the purpose of a cluster?
CLUSTER is a technique used to improve the data retrieval performance.Originally it
is a temporary and logical memory location supports to store multiple tables data in
order to improve data retrieval operations.
Difference between an implicit & an explicit cursor.
Implicit Cursor :
Automatically porvide by oracle which perform DML statements. queries returns only
one row.
We are able to Handle NO_DATA_FOUND Exception.
-
8/14/2019 Oracle 10g PLSQL_1
10/17
Explicit Cursor :
Defined by user. queries returns more than rows.
We are not able to Handle NO_DATA_FOUND Exception.
What are different modes of parameters used in functions and procedures?
-IN
-OUT
-INOUT
How do you find the number of rows in a Table ?
A bad answer is count them (SELECT COUNT(*) FROM table_name)
A good answer is :-
SQL> select count(rowid) from emp;
What is difference between SUBSTR and INSTR?
select substr('abcde',4) gives the output as
de because it counts quotation also as a string so it eliminates till 4 char i.e('abc)and
gives the output as above
select instr('abcde',4) gives the output as 0
SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDEINSTR provides character position in which a pattern is found in a string. eg
INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')
# SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDE
INSTR provides character position in which a pattern is found in a string. eg
INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')
Substr retrieves the string at the required position as Instr retrieves the string
position only.
Can a primary key contain more than one columns?
primary key not allow null values,unique key allow only one null value.In table only
one primary is allowed,unique key as many as it can allow.
-
8/14/2019 Oracle 10g PLSQL_1
11/17
What is difference between Rename and Alias?
Rename is a permanent name given to a table or column whereas Alias is a
temporary name given to a table or column which do not exist once the SQL
statement is executed.
When do you use WHERE clause and when do you use HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and
it is written after GROUP BY clause. The WHERE clause is used when you want to
specify a condition for columns, single row functions except group functions and it is
written before GROUP BY clause if it is used.
where is used to restrict the rowshaving is used to restrict the group
1.where clause is used to restrict
the row ,basically where clauseoperate on single row function
2.Having clause is used to restrict
the groups that means which groups
to be displayed.
What is a cursor for loop?
Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop
index that of the same record type as the cursor's record.
When we use for loops,there is no need to declare explicit cursor.
Only case of for loop,cursor is implicitly open and after fetching the data cursor is
implicitly closed.
Example given below
SET SERVEROUTPUT ON
BEGIN
FOR emp_record IN (SELECT last_name,department_id FROM employees) LOOP
IF emp_record.department_id=80 THEN
DBMS_OUTPUT.PUT_LINE('employees'||'emp_record.last_name'||'works for sales
department');END IF;
END LOOP;--implicit cursor closed
END;
-
8/14/2019 Oracle 10g PLSQL_1
12/17
-
8/14/2019 Oracle 10g PLSQL_1
13/17
Demerit:
The main demerit is again, the whole package is loaded into memory
whenever any procedure/function is called. If only 20% of the procedures/functions
in the package are used, memory consumption gets high for minimal package usage
2. Package, Procedure and Function Syntax:
A package has got 2 components - a Spec and a Body
Spec : is nothing but is like a header which holds all Procedure/Function declarations
and Global variables, collections etc if used.
Body : body has the actual definition of the Stored procedures/Functions. All Data
manipulation is done in the procedures and functions, which are defined in the body.
Eg:
--Spec:
CREATE OR REPLACE PACKAGE EX_PACK_001 --Create package
spec
AS
PROCEDURE EX_PROC_001 --declaring
procedure EX_PROC_001
(
P_NUMBER IN NUMBER,
P_CHAR IN VARCHAR2,P_RET_CODE OUT NUMBER
);
FUNCTION EX_FUNC_001 --declaring function
EX_FUNC_001
(
P_NUMBER IN NUMBER,
P_CHAR IN VARCHAR2
)
RETURN NUMBER;
END EX_PACK_001;
/
--Body:
CREATE OR REPLACE PACKAGE BODY EX_PACK_001
AS
-
8/14/2019 Oracle 10g PLSQL_1
14/17
PROCEDURE EX_PROC_001(P_NUMBER IN NUMBER, P_CHAR IN
VARCHAR2, P_RET_CODE OUT NUMBER)
IS
BEGIN
--CODE HERE--
EXCEPTION
--EXCEPTION BLOCK--
END EX_PROC_001;
FUNCTION EX_FUNC_001(P_NUMBER IN NUMBER, P_CHAR IN VARCHAR2)
RETURN NUMBER
IS
V_CODE NUMBER;
BEGIN
--CODE HERE
RETURN V_CODE;
EXCEPTION
--EXCEPTION BLOCK--
END EX_FUNC_001;
END EX_PACK_001;
3. How to call the packaged procedures/functions in another Program.
Before showing how to call procedures/functions in another Program, I hope
that you know what an anonymous block is. For those who dont know, an
anonymous block is a piece of code that is similar to a procedure but doesnt have
any name or cannot be stored in the database. For eg: the anonymous block below is
used to call our procedure and function, but could not be stored in the DB like the
Package, procedure or function.
Declare
v_code number;
v_number number;
v_char varchar2(50);
-
8/14/2019 Oracle 10g PLSQL_1
15/17
Begin
v_number:=100;
v_char:=Hai;
EX_PACK_001. EX_PROC_001(v_number,v_char,v_code); --
v_code is an OUT parameter
dbms_output.put_line(v_code); --displays datareturned to the OUT param
v_code:= EX_PACK_001. EX_FUNC_001(v_number,v_char); --
function returns the code
dbms_output.put_line(v_code);
end;
/
4. Packaged Procedures versus Normal Procedures
As I had mentioned earlier, packaged procedures can exhibit some of theOOPs behavior.
One main character is polymorphism. In the same package, we can have
different procedures/functions with the same name but different signatures.
Signature is nothing but the parameter list. 2 procedures with same name could
exist in the same package with different number of parameters or different datatypes
for parameters.
For eg:
a. Differs in number of parameters
CREATE OR REPLACE PACKAGE EX_PACK_001 --
showing only spec
AS
PROCEDURE EX_PROC_001
(
P_NUMBER IN NUMBER,
P_CHAR IN VARCHAR2,
P_RET_CODE OUT NUMBER
);
PROCEDURE EX_PROC_001
(
P_NUMBER IN NUMBER,
P_CHAR IN VARCHAR2
) ;
END EX_PACK_001;
-
8/14/2019 Oracle 10g PLSQL_1
16/17
/
b. Differs in datatype of parameters, but same number of parameters
CREATE OR REPLACE PACKAGE EX_PACK_001 --
showing only specAS
PROCEDURE EX_PROC_001
(
P_NUMBER IN NUMBER,
P_CHAR IN VARCHAR2,
P_RET_CODE OUT NUMBER
);
PROCEDURE EX_PROC_001
(
P_CHAR1 IN VARCHAR2,P_CHAR2 IN VARCHAR2,
P_RET_CODE OUT NUMBER
);
END EX_PACK_001;
/
5. Procedure Versus Function
a. Only function can Return a value (to be precise using the Return keyword)
b. Procedures can use Return keyword but without any value being passed
c. Functions could be used in select statements, provided they doesnt do any
data manipulation inside and also should not have any OUT, IN OUT parameters.
6. How to create Private global variables in a Package?
Create variables inside the body (but outside any procedure or function). All
of the functions/procedures in the package can use the variable, but could not be
used outside
7. How to create Private Procedures/Functions?
Write the procedures/functions only in the body. That means, do not declare
the procedure/function in the Spec.
-
8/14/2019 Oracle 10g PLSQL_1
17/17
8. Can a Package Spec exist without a body?
Yes.
Advantage being, we can create global variables or collections and put them
in a package Spec. No need to create any body since there are noprocedures/functions.
Eg:
CREATE OR REPLACE PACKAGE EX_PACK_001
AS
V_RECORDS NUMBER;
END EX_PACK_001;
This variable could be called outside in any code like this:
EX_PACK_001.v_records:=1000;