CH-4 PL-SQL Database Objects & Security
CH-4 PL-SQL Database Objects & Security
What is PL/SQL?
• PL/SQL is a combination of SQL along with the procedural features of programming languages.
• It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
• Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL language code can be
stored in the client system (client-side) or in the database (server-side).
Advantages of PL/SQL
• Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each block
forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused.
• Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional
statements (if else statements) and loops like (FOR loops).
• Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block,
thereby reducing network traffic.
• Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL
program. Once an exception is caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.
PL/SQL identifiers
• PL/SQL identifiers are constants, variables, exceptions, procedures, cursers, & reserved words.
PL/SQL Comments
• The PL/SQL supports single line & multi-line comments.
• Single line comments start with delimiter
-- (double hyphen)
• Multi-line comments are enclosed by /* */.
PL/SQL Variables
• For example:
4. dept varchar2(10) NOT NULL := “HR Dept”;
5. Sal number:=10000;
PL/SQL Constants
• A constant is a value used in a PL/SQL Block that remains unchanged throughout the program.
• General Syntax to declare a constant is:
Constant_name CONSTANT datatype: = VALUE;
• For example:- pi CONSTANT number:=3.14;
• The programming constructs are similar to how you use in programming languages like Java and C++.
• Following is the general form of a typical conditional (i.e., decision making) structure found in most of the
programming languages −
• Conditional Control: - PL/SQL programming language provides following types of decision-making
statements i.e. IF-THEN, IF-THEN-ELSE, IF-THEN-ELSEIF.
1. IF-THEN Statement:-
• For Example:-
IF color = red THEN
dbms_output.put_line (‘you have chosen a red car');
ELSE
dbms_output.put_line (‘please choose a color for your car');
END IF;
• Flow Diagram
Sample Example 1:-
• The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add
additional conditions.
• Syntax for IF-THEN-ELSIF statement
IF (boolean_expression 1) THEN
S1; - - Executes when the Boolean expression 1 is true
ELSIF (boolean_expression 2) THEN
S2; - - Executes when the Boolean expression 2 is true
ELSIF (boolean_expression 3) THEN
S3; - - Executes when the Boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
• For Example 1
• Syntax
CASE [expression]
WHEN condition_1 THEN result_1;
……………
END CASE;
• Flow Diagram
Sample Example 1:-
• Syntax
FOR counter IN initial_value. . final_value LOOP
sequence_of_statements;
END LOOP;
1. Write a PL/SQL program to print even or odd number from given range (Accept number range from
user).
Ans: - NOTE: - In above program it specified that given range so that we used FOR LOOP
DECLARE
A Number;
B Number;
BEGIN
a: =&A;
b: =&B;
FOR i IN a . . b LOOP
IF (mod (i, 2):=0) THEN
Dbms_output.Put_line (i);
END If;
END Loop;
END;
DECLARE
A Number;
B Number;
BEGIN
a: =&A;
b: =&B;
FOR i IN a . . b LOOP
IF (mod (i, 2):=1) THEN
Dbms_output.Put_line (i);
END If;
END Loop;
END;
2. Write PL/SQL program to display factorial of any number.
DECLARE
f number: =1;
n number := &n;
i number;
BEGIN
FOR i IN 1..n LOOP
f := f * i;
END LOOP;
dbms_output.put_line (f);
END;
/
3. Write a PL/SQL program to find the square of a number given by user using WHILE….LOOP. (accept
the number from user dynamically)
DECLARE
n number:= &n;
sqr number: = 0;
n_cntr number: =0;
BEGIN
Dbms_Output.Put_Line (N);
WHILE n_cntr < n LOOP
sqr: = sqr + n;
n_cntr:= n_cntr + 1;
END LOOP;
Dbms_Output.Put_Line (‘square of ' || n || ' is ' || sqr);
END;
/
Exception Handling
Errors:-
• Two types of errors can be found in a program: compilation errors and runtime errors.
• There is a special section in a PL/SQL block that handles the runtime errors.
• This section is called the exception-handling section, and in it, runtime errors are referred to as
exceptions.
• The exception-handling section allows programmers to specify what actions should be taken when a
specific exception occurs.
Exception:-
• In order to handle run time errors in the program, an exception handler must be added.
• Exception handling is nothing but a code block in memory that will attempt to resolve current error
condition.
• The exception-handling section has the following structure:
EXCEPTION
WHEN Exception_name THEN
Error-processing Statements;
• Note: - The exception-handling section is placed after the executable section of the block.
DECLARE
--Declaration section
BEGIN
-- Program section
--Exception section
EXCEPTION
WHEN ex_name1 THEN
--Error handling statements
WHEN ex_name2 THEN
--Error handling statements
END;
• Exception Handling Example:
DECLARE Output:-
num1 number := &sv_num1;
num2 number := &sv_num2; Enter value for sv_num1: 4
result number;
BEGIN Enter value for sv_num2: 0
result := num1 / num2; A number cannot be divided by zero.
DBMS_OUTPUT.PUT_LINE ( ‘the is result: ’|| result);
EXCEPTION PL/SQL procedure successfully completed.
WHEN ZERO_DIVIDE
THEN
DBMS_OUTPUT.PUT_LINE (‘A number cannot be divided
by zero.’);
END;
/
a) Predefined Exceptions:-
• System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
• There are some system exceptions which are raised frequently, so they are pre-defined and given a
name in Oracle which are known as Named System Exceptions.
• For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
• Named system exceptions are:
1) not declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs.
3) Caught by referencing the standard name within an exception-handling routine.
• This type of an exception is called a user-defined exception because it is defined by the programmer.
• Before the exception can be used, it must be declared.
• It must be declare by the user in the declaration part of the block where the exception is used.
• A user-defined exception is declared in the declarative part of a PL/SQL block as shown below:
DECLARE
Exception_name EXCEPTION;
• Once an exception has been declared, the executable statements associated with this exception are
specified in the exception-handling section of the block.
• User-defined Exceptions Example
DECLARE
E_invalid_id EXCEPTION;
BEGIN
………
EXCEPTION
WHEN E_invalid_id THEN
Dbms_output.Put_line (‘An Id Cannot Be Negative‘ );
END;
/
c) Raising Exceptions
• Exceptions are raised by the database server automatically whenever there is any internal database
errors, but exceptions can be raised explicitly by the programmer by using the command RAISE.
• Example
DECLARE
Exception_name EXCEPTION
BEGIN
IF (condition) THEN
RAISE Exception_name;
END IF;
EXCEPTION
WHEN Exception_name THEN
dbms_output.put_line (' Raising Exceptions ');
END;
5.2 Cursor
• A cursor is a temporary work area created in the system memory when a SQL statement is executed.
• A cursor contains information on a select statement and the rows of data accessed by it.
• This temporary work area is used to store the data retrieved from the database, and manipulate this data.
• A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor
holds is called the active set.
• A cursor is a pointer to this context area.
• PL/SQL controls the context area through a cursor.
1. Implicit cursors
• If database engine opens a cursor for internal processing, it is called as implicit cursor.
• These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements
are executed. They are also created when a SELECT statement that returns just one row is executed.
• When you execute DML statements like INSERT, UPDATE, DELETE & SELECT statements, implicit
statements are created to process these statements.
• Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations.
• The cursor attributes available are:-
DECLARE
total_rows number (2);
BEGIN
Update EMP set salary= salary +1500 where empno =10;
If SQL%FOUND then
Dbms_out.put_line (‘Emp table modified’);
Else
Dbms_out.put_line (‘Emp table not modified’);
End if;
END;
2. Explicit Cursors
• A user can open a cursor for processing data as required. Such user defined cursors are known as
explicit cursors.
• It should be defined in the declaration section of the PL/SQL block.
• They must be created when you are executing a SELECT statement that returns more than one row.
• Both implicit and explicit cursors have the same functionality, but they differ in the way they are
accessed.
• General Syntax for creating a cursor is as given below:
• Step1: DECLARE the cursor: - Define cursor with a name & the associated SELECT statement.
• For example:-
CURSOR c_customers IS SELECT id, name, address FROM
customers;
• For example:-
OPEN c_customers;
• Step3: FETCH the data from cursor into PL/SQL variables or records in the Execution Section.
• Step4: CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
• For example:-
CLOSE c_customers;
Write pl/sql program for displaying details of student studying in computer department using cursor
create table student(student_id number(3),first_name varchar2(10),last_name
varchar2(10),department varchar2(10));
insert into student values(1,'tina','patil','computer');
insert into student values(2,'priya','pandhe','computer');
insert into student values(3,'om','taware','IT');
insert into student values(4,'shalini','patil','mech');
insert into student values(5,'tanmay','patil','mech');
insert into student values(6,'shital','ghanwat','computer');
select *from student;
declare
cursor student_cur IS
select student_id,first_name,last_name,department from student where department='computer';
student_rec student_cur%rowtype;
begin
open student_cur;
loop
fetch student_cur into student_rec;
exit when student_cur%notfound;
dbms_output.put_line ('student_id:'||student_rec.student_id);
dbms_output.put_line ('first_name:'||student_rec.first_name);
dbms_output.put_line ('last_name:'||student_rec.last_name);
dbms_output.put_line ('department:'||student_rec.department);
end loop;
close student_cur;
end;
declare
cursor c1 is select * from student ;
e_rec student %rowtype;
row_count number:=0;
begin
for e_rec in c1
loop
row_count:=row_count+1;
if mod(row_count,2)=1 then
dbms_output.put_line(e_rec.student_id||' '||e_rec.first_name||' '||e_rec.last_name||'
'||e_rec.department||' ');
end if;
exit when c1 %notfound;
end loop;
end;
5.3 Procedures
• A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific
task. This is similar to a procedure in other programming languages.
• A procedure has a header and a body.
• The header consists of the name of the procedure and the parameters or variables passed to the
procedure.
• The body consists of declaration section, execution section and exception section similar to a general
PL/SQL Block.
• A procedure is a module performing one or more actions; it does not need to return any values.
• The syntax for creating a procedure is as follows:
• Where,
• Example
Output:-
SQL> Procedure Created.
• Executing a Standalone Procedure
• Types of Parameters
create or replace procedure proc1
as
begin
dbms_output.put_line('hello world');
end;
—---call to procedure
begin
proc1;
end;
• Example of Procedures (Write PL/SQL Program to finds the minimum number of two values)
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number)
IS
BEGIN
IF x < y THEN
z: = x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
FindMin (a, b, c);
dbms_output.put_line (' minimum of (23, 45): ' || c);
END;
/
5.4 Functions
• Functions are a type of stored code and are very similar to procedures.
• The significant difference is that a function is a PL/SQL block that returns a single value.
• Functions can accept one, many, or no parameters, but a function must have a return clause in the
executable section of the function.
• The datatype of the return value must be declared in the header of the function.
• A function has output that needs to be assigned to a variable, or it can be used in a SELECT statement.
• The syntax for creating a function is as follows:
• When the above code is executed using the SQL prompt, it will produce the following result −
DECLARE
c number(2);
BEGIN
c := totalCustomers(); -- function call
dbms_output.put_line ('Total no. of Customers: ' || c);
END;
/
• When the above code is executed at the SQL prompt, it produces the following result –
Output:-
SQL> Total no. of Customers: 5
PL/SQL procedure successfully completed.
• Example of Function
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
Output
SQL> Maximum of (23, 45): 45
PL/SQL procedure successfully completed.
Deleting a procedures:-
• PL/SQL procedure is remove from the database by using the drop procedure command.
• Syntax:- DROP PROCEDURE procedure_name;
• Example:- DROP PROCEDURE greetings
Deleting a Function:-
• PL/SQL procedure is remove from the database by using the drop function command.
Procedure Function
It may return a value or not. It must return a value.
Where,
Trigger Example
• The following program creates a row-level trigger for the customers table that would fire for INSERT
or UPDATE or DELETE operations performed on the CUSTOMERS table. (referred above table 1)
• Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table −
SQL> INSERT INTO CUSTOMERS VALUES (7, 'Kriti', 22, 'HP', 7500.00);
Old salary:
New salary: 7500
Salary difference: