Wordpress Material Rdbms U 4
Wordpress Material Rdbms U 4
Unit – IV
PL/ SQL and Triggers
4.1 Basics of PL / SQL
• PL/SQL is super set of the SQL. So, it supports all the data types provided by SQL.
• Along with this, in PL/SQL Oracle provides subtypes of the data types.
• For example, the data type NUMBER has a subtype called INTEGER.
• These subtypes can be used in PL/SQL block to make the data type compatible with the
data types of the other programming languages.
1) Procedural Capabilities:
• PL/SQL provides procedural capabilities such as condition checking, branching and
looping.
• This enables programmer to control execution of a program based on some conditions
and user inputs.
2) Support to variables:
• PL/SQL supports declaration and use of variables.
• These variables can be used to store intermediate results of a query or some expression.
3) Error Handling:
• When an error occurs, user friendly message can be displayed.
• Also, execution of program can be controlled instead of abruptly terminating the
program.
5) Portability:
• Programs written in PL/SQL are portable.
• It means, programs can be transferred and executed from any other computer hardware
and operating system, where Oracle is operational.
6) Sharing of Code:
• PL/SQL allows user to store compiled code in database. This code can be accessed and
shared by different applications.
• This code can be executed by other programming language like JAVA.
•
To create and execute a PL/SQL block, follow the steps given below:
•
Open any editor like as notepad. An EDIT command can be used on SQL prompt to open
a notepad from the SQL * PLUS environment.
• The following syntax creates and opens a file:
EDIT filename
Example:
EDIT D:/PLSQL/test.sql
• Create and open a file named ‘test.sql’.
• Write a program code or statements in a file and save it.
• File should have ‘.sql’ extension and last statement in file should be ‘/’.
Example:
@ D:/PLSQL/test.sql
• In PL/SQL , the flow of execution can be controlled in three different manners as given
below:
o Conditional Control
o Iterative Control
o Sequential Control
1) Conditional Control:
• To control the execution of block of code based on some condition, PL/SQL provides the
IF statement.
• The IF – THEN – ELSEIF – ELSE – END IF construct can be used to execute specific
part of the block based on the condition provided.
Syntax:
IF condition THEN
-- Execute commands
ELSIF condition THEN
--- Execute commands
ELSE
--- Execute commands
END IF;
Example:
Declare
n number:=&n;
Begin
if mod(n,2)=0 then
dbms_output.put_line('number is even');
else
dbms_output.put_line('number is odd');
end if;
End;
/
2) Iterative Control:
• In PL/SQL, any loop starts with a LOOP keyword and it terminates with an END
LOOP keyword.
• Each loop requires a conditional statement to control the number of times a loop is
executed.
1. LOOP
Syntax:
LOOP
-- Execute commands
END LOOP
Example:
DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
2. WHILE
Syntax:
WHILE Condition
LOOP
-- Execute commands
END LOOP
• The WHILE loop executes commands in its body as long as the condition remains
TRUE.
• The loop terminates when the condition evaluates to FALSE or NULL.
• The EXIT statement can also be used to exit the loop.
Example:
DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 10
LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
3. FOR
Syntax:
FOR counter IN initial_value .. final_value
LOOP
statements;
END LOOP;
Example:
DECLARE
k INTEGER;
BEGIN
FOR k IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (k);
END LOOP;
END;
3) Sequential Control:
Syntax:
GOTO label_name;
..
..
<<label_name>>
Statement;
Example:
DECLARE
a number(2) := 10;
BEGIN
<<loopstart>>
WHILE a < 20
LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
• Run-time errors can be handled in some useful way rather than getting system specific
message and terminating program directly. It’s called exception handling.
There are two types of exception:
1) System Exception: In PL/SQL, various run-time errors are associated with different
exceptions. These types of exceptions are known as system exception.
2) User-defined Exception: User also can define their own exception is known as user-
defined exception.
• Exception handler scans the PL/SQL block to check existence of the Exception
Handling section within block.
Syntax:
EXCEPTION
❖ Types of Exceptions
o Named Exceptions
o Numbered Exceptions
1) Named Exceptions:
Create an Account with Acc_No as a primary key. Write a PL/SQL block to insert a record in
this table. Also handle named exceptions DUP_VAL_ON_INDEX. Which is raised on
encountering duplicate value for primary or unique key. (Assume table is available)
DECLARE
-- declare required variable
no Account.Acc_No%TYPE;
bal Account.Balance%TYPE;
branch Account.B_Name%TYPE;
BEGIN
--read an account number, balance and branch name for new record no := &no;
bal := &bal;
branch := &branch;
--insert record into Account table
INSERT INTO Account VALUES (no, bal, branch); --commit and display message confirming
insertion
COMMIT;
dbms_output.put_line(‘Record inserted successfully.’);
EXCEPTION
--handle named exception
Output:
Enter value for no: ‘A01’
Enter value for bal: 5000
Enter value for no: ‘RJT’
Record inserted successfully
2) Numbered Exceptions:
• These exceptions are identified by using negative signed number, such as -1200.
• Oracle has defined more than 20000 numbered exceptions.
Syntax:
DECLARE
exceptionName EXCEPTION;
BEGIN
--execute commans . . .
EXCEPTION
WHENexcepetionName THEN
END ;
/
• A PRAGMA is a call to pre-compiler that binds the numbered exception to some name.
• A function EXCEPTION_INIT takes two parameters: one is exception name and number
of the exception to be handled.
• Once binding is provided, exception can be handle in exception handling section using
WHEN clause.
Example: Along with named exception, in above example also handle numbered exception with
number -1200, which is raised on encountering for primary or NOT NULL key. (Assume table is
available)
DECLARE
exNull EXCEPTION;
PRAGMA EXCEPTION_INIT (exNull, -1200);
no Account.Acc_No%TYPE;
bal Account.Balance%TYPE;
branch Account.B_Name%TYPE;
BEGIN
--read an account number, balance and branch name for new record
no := &no;
bal := &bal;
branch := &branch;
EXCEPTION
Output 1 :
Enter value for no: ‘A02’
Enter value for bal: 6000
Enter value for no: ‘RJT’
Record inserted successfully.
Output 2 :
Enter value for no: null
Enter value for bal: 10000
Enter value for no: ‘SRT’
Null value found for primary key.
3) User-defined Exceptions:
• User also can define their own exceptions are known as user define exceptions.
• These exceptions are used to validate business rules like balance for any account should
not be negative value.
• User-defined exceptions need to be declared, raised and handled explicitly.
Syntax:
DECLARE
exceptionName EXCEPTION ;
BEGIN
--SQL and PL/SQL statement
IF condition THEN
RAISE exceptionName
END IF ;
EXCEPTION
END ;
DECLARE
exNull EXCEPTION;
PRAGMA EXCEPTION_INIT (exNull, -1200);
myEx EXCEPTION;
no Account.Acc_No%TYPE;
bal Account.Balance%TYPE;
branch Account.B_Name%TYPE;
BEGIN
--read an account number, balance and branch name for new record no := &no;
bal := &bal;
branch := &branch;
EXCEPTION
END;
/
Output 1 :
Enter value for no: ‘A03’
Enter value for bal: 6000
Enter value for no: ‘RJT’
Record inserted successfully.
Output 2 :
Enter value for no: ‘A04’
Enter value for bal: -10000
Enter value for no: ‘SRT’
Balance cannot be negative value.
• Row Pointer: A pointer that is used to track the current row is known as Row Pointer.
• Cursor Attributes: Multiple cursor variables are used to indicate the current status of the
processing being done by the cursor. These kinds of variables are known as Cursor
Attributes.
Attribute Description
o Implicit Cursor
o Explicit Cursor
1) Implicit Cursor:
SQL%AttributeName
• The value of the cursor attribute always refers to the SQL command that was executed
most recently.
• Before open implicit cursor, its attribute contains NULL as value.
Example:
DECLARE
BEGIN
END;
/
Output 1:
Enter value for branch: ‘surat’
Given branch not available.
Output 2 :
Enter value for branch:’RJT’
Total 2 records are updated.
2) Explicit Cursor:
❖ Declare a Cursor:
Syntax:
CURSOR cursorName IS SELECT …. ;
• A cursor with cursorName is declared.
• It is mapped to a query given by SELECT statement.
• Here, only cursor will be declared. No any memory is allocated yet.
Example:
CURSOR cursorAcc IS
SELECT Acc_No, Balance, B_Name FROM Account ;
❖ Open a Cursor:
Syntax:
OPEN cursorName ;
❖ Fetching Data:
• We cannot process selected row directly. We have to fetch column values of a row into
memory variables.
• This is done by FETCH statement.
Syntax:
FETCH cursorName INTO variable1, variable2………. ;
• Retrieve data from the current row in the active data set and stores them in given
variables.
• Data from a single row are fetched at a time.
• After fetching data, updates row pointer to point the next row in an active data set.
• Variables should be compatible with the columns specified in the SELECT statement.
Example:
FETCH cursorAcc INTO no, balance, bname ;
• Fetched account number, balance and branch name from current row in active data set
and store them in respective variables.
• To process more than one record, the FETCH statement is enclosed within loop like
❖ Processing data:
• This step involves actual processing of current row by using PL/SQL as well as SQL
statements..
❖ Closing Cursor:
• A cursor should be closed after the processing of data completes. Once you close the
cursor it will release memory allocated for that cursor.
• If user forgets to close the cursor, it will be automatically closed after termination of the
program.
Syntax:
CLOSE cursorName ;
SQL%AttributeName
Example:
DECLARE
-- declare a cursor
CURSOR cursorAcc IS
SELECT Acc_No, Balance, B_Name FROM Account ;
--declare required variables
no Account.Acc_No%TYPE ;
balance Account.Balance%TYPE;
branch Account.B_Name%TYPE;
BEGIN
--open a cursor
OPEN cursorAcc ;
--if no record available in active data set then exit from loop
EXIT WHEN cursorAcc%NOTFOUND ;
END IF ;
END LOOP;
ELSE
dbms_output.put_line (‘Cursor cannot be opened.’) ;
END IF ;
END ;
/
❖ Creating a Procedure
Syntax:
❖ Executing a Procedure
Syntax:
EXECUTE [or EXEC] procedure_name (parameter) ;
Example:
❖ Creating a Function
Syntax:
CREATE [OR REPLACE] FUNCTION func_name (argument IN dataType…)
RETURN dataType
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END ;
Example:
Create or replace function adder(n1 in number, n2 in number)
Return number
Is
n3 number(8);
Begin
n3 :=n1+n2;
Return n3;
End;
/
❖ Executing a Function
Syntax:
SELECT function_name (parameter) FROM dual ;
• A trigger is a group or set of SQL and PL/SQL statements that are executed by Oracle
itself.
• The main characteristic of the trigger is that it is fired automatically when DML
statements like Insert, Delete, and Update is executed on a table.
• The advantages of triggers are as given below:
o To prevent misuse of database.
o To implement automatic backup of the database.
o To implement business rule constraints, such as balance should not be negative.
o Based on change in one table, we want to update other table.
o To track the operation being performed on specific tables with details like
operation, time when it is performed, user name who performed it, etc..
• In a row level trigger, the trigger fires for each related row. And sometimes it is required
to know the value before and after the DML statement.
• Oracle has provided two clauses in the RECORD-level trigger to hold these values. We
can use these clauses to refer to the old and new values inside the trigger body.
• :NEW – It holds a new value for the columns of the base table/view during the trigger
execution
• :OLD – It holds old value of the columns of the base table/view during the trigger
execution
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Example:
DECLARE
age_diff number;
BEGIN
age_diff := :NEW.age - :OLD.age;
dbms_output.put_line ('Prevoius age: ' || : OLD.age);
dbms_output.put_line ('Current age: ' || : NEW.age);
dbms_output.put_line ('Age difference: ' || age_diff);
END;
/
4.9 Types of Triggers: Before, after for each row, for each statement
Triggers can be classified based on the following parameters.
• STATEMENT level Trigger: It fires one time for the specified event statement.
• ROW level Trigger: It fires for each record that got affected in the specified event. (only
for DML)