You are on page 1of 45

Unit-10

PL/SQL Concepts
Cursor
Cursor
 Cursors are database objects used to traverse the results of a
select SQL query.
 It is a temporary work area created in the system memory
when a select SQL statement is executed.
 This temporary work area is used to store the data retrieved
from the database, and manipulate this data.
 It points to a certain location within a record set and allow
the operator to move forward (and sometimes backward,
depending upon the cursor type).
 We can process only one record at a time.
 The set of rows the cursor holds which is called the active set
(active data set).
 Cursors are often criticized for their high overhead.
Types of cursor
 There are two types of cursors in PL/SQL:
1. Implicit cursors
2. Explicit cursors
Implicit cursors:
 Implicit cursors are automatically created by Oracle
whenever an SQL statement is executed, when there is no
explicit cursor for the statement.
 Programmers cannot control the implicit cursors and the
information in it.
 Whenever a DML statement (INSERT, UPDATE and DELETE)
is issued, an implicit cursor is associated with this statement.
For INSERT operations, the cursor holds the data that needs
to be inserted. For UPDATE and DELETE operations, the
cursor identifies the rows that would be affected.
 In PL/SQL, you can refer to the most recent implicit cursor as
the SQL cursor, which always has attributes such as
%FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
Implicit cursors Attributes
Sr.No Attribute & Description
1. %FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement
affected one or more rows or a SELECT INTO statement returned
one or more rows. Otherwise, it returns FALSE.
2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
UPDATE, or DELETE statement affected no rows, or a SELECT
INTO statement returned no rows. Otherwise, it returns FALSE.
3 %ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes
the SQL cursor automatically after executing its associated SQL
statement.
4 %ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.
For write a Program:
 Declaration Section (Optional)
DECLARE
 Executable Section , From BEGIN to END
 For display output,
DBMS_OUTPUT.PUT_LINE(‘ ‘);
Program:
 CUSTOMERS table
Program:
The following program will update the table and increase the
salary of each customer by 500 and use the SQL%ROWCOUNT
attribute to determine the number of rows affected −
DECLARE
total_rows number(6);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
Output:
When the code is executed at the SQL prompt, it produces the
following result −
6 customers selected
PL/SQL procedure successfully completed.
Select * from customers;
Explicit cursors:
• Explicit cursors are user defined cursors written by the
developer.
• They can be created when a SELECT statement returns more
than one row.
• Even though the cursor stores multiple records, only one record
can be processed at a time, which is called as current row.
• When you fetch a row, the current row position moves to next
row.
• The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Here:
cursorName – This represents a valid name for the cursor
Select Statement – This represents a select query that will return
multiple rows
Life cycle of explicit cursor
Steps to manage explicit cursor
Declare Cursor:
 A cursor is declared by defining the SQL statement that
returns a result set
 Declaring the cursor defines the cursor with a name and the
associated SELECT statement.
 For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Steps to manage explicit cursor
Open:
 A Cursor is opened and populated by executing the SQL
statement defined by the cursor.
 Opening the cursor allocates the memory for the cursor and
makes it ready for fetching the rows returned by the SQL
statement into it.
 For example, we will open the above defined cursor as follows
OPEN c_customers;
Steps to manage explicit cursor
Fetch:
 When the cursor is opened, rows can be fetched from the
cursor one by one or in a block to perform data
manipulation.
 Fetching the cursor involves accessing one row at a time.
 For example, we will fetch rows from the above-opened cursor
as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Steps to manage explicit cursor
Close:
 After data manipulation, close the cursor explicitly.
 Closing the cursor means releasing the allocated memory.
 For example, we will close the above-opened cursor as follows
CLOSE c_customers;

Deallocate:
Finally, delete the cursor definition and release all the system
resources associated with the cursor.
How to use explicit cursor?
 There are four steps in using an Explicit Cursor.
1. DECLARE the cursor in the Declaration section.
2. OPEN the cursor in the Execution Section.
3. FETCH the data from the cursor into PL/SQL
variables or records in the Execution Section.
4. CLOSE the cursor in the Execution Section before
you end the PL/SQL Block.
Syntax of explicit cursor
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Program
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output:
When the code is executed at the SQL prompt, it produces the
following result
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Triggers
Triggers
 A trigger is a PL/SQL block structure which is
triggered (executed) automatically when DML
statements like Insert, Delete, and Update is
executed on a table.
 They are invoked by oracle engine automatically when
a specified event occurs.
 Are stored program in database and are invoked
repeatedly when specific condition matches.
 Can Be written in response of following events.
1. Data Definition Language (DDL) triggers
2. Data Manipulation Language (DML) triggers
3. Logon triggers
Components of Trigger (E-C-A Model)
Event (E):
 SQL statement that cause the trigger to fire .This event may be
insert, update or delete operation database table.
Condition(C):
 A condition that must be satisfied for execution of trigger.
Action(A) :
 This is code or statement that execute when triggering
condition is satisfied and trigger is activated on database table.
Creating Triggers
The syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS , NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Trigger Parameters
Trigger types
1. Row level triggers
2. Statement level triggers
Trigger types
Row level triggers:
 A row level trigger is executed each time when table is affected
by the triggering statement.
 Example: If an UPDATE statement changes multiple row in a
table, a row trigger is fired once for each row affected by the
UPDATE statement.
 If a triggering statement do not affects any row then a row
trigger will not run only.
 If FOR EACH ROW clause is written that means trigger is row
level trigger.
Trigger types
Statement level triggers:
 A statement level trigger is fired only once on behalf of the
triggering statement, irrespective of the number of rows in the
table that are affected by the triggering statement.
 This trigger execute once even if no rows are affected.
 Example: If a DELETE statement deletes several rows from a
table, a statement level DELETE trigger is fired only one time.
 This is default type, when FOR EACH ROW clause is not written
in trigger that means trigger is statement level trigger.
Example of triggers
Creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the
CUSTOMERS table. This trigger will display the salary difference
between the old values and new values.
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
Example of triggers
Output:
Trigger created.
The following points need to be considered here −
 OLD and NEW references are not available for table-level
triggers, rather you can use them for record-level triggers.
 If you want to query the table in the same trigger, then you
should use the AFTER keyword, because triggers can query the
table or change it again only after the initial changes are
applied and the table is back in a consistent state.
 The above trigger has been written in such a way that it will
fire before any DELETE or INSERT or UPDATE operation on the
table, but you can write your trigger on a single or multiple
operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation
on the table.
Example of triggers
Let us now perform one more DML operation on the CUSTOMERS
table. The UPDATE statement will update an existing record in the
table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above
create trigger, display_salary_changes will be fired and it will
display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table.
Here is one INSERT statement, which will create a new record in
the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above
create trigger, display_salary_changes will be fired and it will
display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the
above result comes as null.
Advantages of Trigger
 Generating some derived column values automatically
 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Stored
Procedure
Stored procedure
 A stored procedure (proc) is a group of PL/SQL statements
that performs specific task.
 A procedure has two parts, header and body.
 The header consists of the name of the procedure and the
parameters passed to the procedure.
 The body consists of declaration section, execution section
and exception section.
 A procedure may or may not return any value. A procedure
may return more than one value.
 A stored procedure is a prepared SQL code that you can save,
so the code can be reused over and over again.
 So if you have an SQL query that you write over and over again,
save it as a stored procedure, and then just call it to execute it.
 You can also pass parameters to a stored procedure, so that the
stored procedure can act based on the parameter value(s) that
is passed.
Stored procedure (Syntax)
 CREATE [OR REPLACE] PROCEDURE procedure_name
[list of parameters]
AS
BEGIN
sql_statement
END
 Execute a Stored Procedure
EXEC procedure_name;
Stored procedure
 Create:-It will create a procedure.
 Replace :- It will re-create a procedure if it already exists.
 We can pass parameters to the procedures in three ways.
1. IN-parameters: - These types of parameters are used to send values to
stored procedures.
2. OUT-parameters: - These types of parameters are used to get values
from stored procedures. This is similar to a return type in functions
but procedure can return values for more than one parameters.
3. IN OUT-parameters: - This type of parameter allows us to pass values
into a procedure and get output values from the procedure.
Stored procedure
 AS indicates the beginning of the body of the procedure.
 sql_statement contains the SQL query. (select, insert, update or
delete)
 The syntax within the brackets [ ] indicates that they are
optional.
 By using CREATE OR REPLACE together the procedure is
created if it does not exist and if it exists then it is replaced
with the current code.
How to execute a stored procedure?
 There are two ways to execute a procedure.
1. From the SQL prompt.
Syntax: EXECUTE [or EXEC] procedure_name (parameter);

2. Within another procedure: simply use the procedure name.


Syntax: procedure_name (parameter);
Example of stored procedure
 CREATE [OR ALTER] PROCEDURE spGet_studentname_by_id
@id int
@ dept varchar2()
AS
BEGIN
SELECT studentname FROM student WHERE studentID = @id,
Studentdept=@dept;
END
 Execute:- EXEC spGet_studentname_by_id 10 ,’COMPUTER’

 Explanation:- Above procedure gives the name of student


whose id is 10.
Advantages of stored procedure
 Security:- We can improve security by giving rights to
selected persons only.
 Faster Execution:- It is precompiled so compilation of
procedure is not required every time you call it.
 Sharing of code:- Once procedure is created and stored, it can
be used by more than one user.
 Productivity:- Code written in procedure is shared by all
programmers. This eliminates redundant coding by multiple
programmers so overall improvement in productivity.
Difference between SQL and PLSQL
SQL PL/SQL
It is a database programming language
It is a database Structured Query Language.
using SQL.
Data variable are not available Data variable are available.
Control Structures are available Like, For
No Supported Control Structures.
loop, While loop.
PLSQL block performs Group of Operation
Query performs single operation.
as single bloack.
SQL is declarative language. PLSQL is procedural language.
SQL can be embedded in PLSQL. PLSQL can’t be embedded in SQL.
It does not interacts directly with the
It directly interacts with the database server.
database server.
It is Data oriented language. It is application oriented language.
It is accustomed write program blocks,
It is used to write queries, DDL and DML
functions, procedures triggers, and
statements.
packages.
Program
Write a PL/SQL program for inserting even numbers in EVEN table and
odd number in ODD table from number 1 to 50. (Winter-2017)
SOLUTION:
DECLARE
BEGIN
FOR i IN 1..50 LOOP
IF MOD(i,2)= 0 THEN
INSERT INTO EVEN VALUES(i);
ELSE
INSERT INTO ODD VALUES(i);
END IF;
END LOOP;
COMMIT;
END;
Program
Write a PL/SQL block to print the sum of Numbers from 1 to 100. (Summer-19)
SOLUTION :
DECLARE
A NUMBER;
SUM1 NUMBER :=0;
BEGIN
A:=1;
LOOP
SUM1:=SUM1+A;
EXIT WHEN (A=100);
A:=A+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM BETWEEN 1 TO 100 IS '||SUM1);
END;
Write a PL/SQL block to print the given number is prime or not. (Summer-19)
SOLUTION:
DECLARE
NUM NUMBER;
I NUMBER:=1;
C NUMBER:=0;
BEGIN
NUM:=#
FOR I IN 1..NUM
LOOP
IF((MOD(NUM,I))=0)
THEN
C:=C+1;
END IF;
END LOOP;
IF(C>2)
THEN
DBMS_OUTPUT.PUT_LINE(NUM||' NOT A PRIME');
ELSE
DBMS_OUTPUT.PUT_LINE(NUM||' IS PRIME');
END IF;
END; /

You might also like