0% found this document useful (0 votes)
24 views

PL/SQL Notes

PL/SQL is a block structured language that is closely integrated with SQL. It allows developers to perform procedural programming by adding conditions, loops, variables, and other control structures. PL/SQL code can be stored in a database as procedures, functions, packages and triggers to be reused by applications.

Uploaded by

Jack Sparrow
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

PL/SQL Notes

PL/SQL is a block structured language that is closely integrated with SQL. It allows developers to perform procedural programming by adding conditions, loops, variables, and other control structures. PL/SQL code can be stored in a database as procedures, functions, packages and triggers to be reused by applications.

Uploaded by

Jack Sparrow
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

PL/SQL

DEFINITION
• PL/SQL is a block structured language. The
programs of PL/SQL are logical blocks that can
contain any number of nested sub-blocks. Pl/SQL
stands for "Procedural Language extension of SQL"
that is used in Oracle.
• Although PL/SQL is closely integrated with SQL
language, yet it adds some programming
constraints that are not available in SQL.
PL/SQL Functionalities

• PL/SQL includes procedural language elements like


conditions and loops.
• It allows declaration of constants and variables,
procedures and functions, types and variable of
those types and triggers.
• It can support Array and handle exceptions (runtime
errors).
• You can create PL/SQL units like procedures,
functions, packages, types and triggers, etc. which
are stored in the database for reuse by applications.
Contd..
• The PL/SQL is known for its combination of data manipulating
power of SQL with data processing power of procedural
languages. It inherits the robustness, security, and portability
of the Oracle Database.
• PL/SQL is not case sensitive so you are free to use lower case
letters or upper case letters except within string and character
literals. A line of PL/SQL text contains groups of characters
known as lexical units. It can be classified as follows:
– Delimiters
– Identifiers
– Literals
– Comments (Single line – double hypen; Multi line - /* … */)
PL/SQL Variables

• A variable is a meaningful name which facilitates a programmer to store data


temporarily during the execution of code.
• A variable should not exceed 30 characters. Its letter optionally followed by more
letters, dollar signs, numerals, underscore etc.
• You must declare the PL/SQL variable in the declaration section or in a package as
a global variable. After the declaration, PL/SQL allocates memory for the variable's
value and the storage location is identified by the variable name.
• Syntax for declaring variable:
• Following is the syntax for declaring variable:
• variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
• Counter integer := 0;
• msg varchar2(20) DEFAULT 'Hello World';

• For constant
• pi constant number := 3.141592654;
Example
• DECLARE
• a integer := 30;
• b integer := 40;
• c integer;
• f real;
• BEGIN
• c := a + b;
• dbms_output.put_line('Value of c: ' || c);
• f := 100.0/3.0;
• dbms_output.put_line('Value of f: ' || f);
• END;
• /
Variable Scope in PL/SQL:
• Local Variable: Local variables are the inner
block variables which are not accessible to
outer blocks.
• Global Variable: Global variables are declared
in outermost block.
Eg
• DECLARE
• -- Global variables
• num1 number := 95;
• num2 number := 85;
• BEGIN
• dbms_output.put_line('Outer Variable num1: ' || num1);
• dbms_output.put_line('Outer Variable num2: ' || num2);
• DECLARE
• -- Local variables
• num1 number := 195;
• num2 number := 185;
• BEGIN
• dbms_output.put_line('Inner Variable num1: ' || num1);
• dbms_output.put_line('Inner Variable num2: ' || num2);
• END;

• END;
• /
PL/SQL Literals

• Numeric Literals
• Character Literals
• String Literals
• BOOLEAN Literals
• Date and Time Literals
PL/SQL If
IF condition
• IF condition
THEN
• THEN {...statements to execute when condition is T
• Statement: {It is executed when conditi RUE...}
on is true} ELSE
• END IF; {...statements to execute when condition is F
ALSE...}
END IF;

IF condition1 IF condition1
THEN THEN
{...statements to execute when condition1 is TRUE...} {...statements to execute when condition1 is TRUE...}
ELSIF condition2 ELSIF condition2
THEN THEN
{...statements to execute when condition2 is TRUE...} {...statements to execute when condition2 is TRUE...}
END IF; ELSE
{...statements to execute when both condition1 and condit
ion2 are FALSE...}
END IF;
Eg
• DECLARE
• a number(3) := 500;
• BEGIN
• -- check the boolean condition using if statement
• IF( a < 20 ) THEN
• -- if condition is true then print the following
• dbms_output.put_line('a is less than 20 ' );
• ELSE
• dbms_output.put_line('a is not less than 20 ' );
• END IF;
• dbms_output.put_line('value of a is : ' || a);
• END;
PL/SQL Case Statement

• The PL/SQL CASE statement facilitates you to execute a


sequence of satatements based on a selector. A selector can
be anything such as variable, function or an expression that
the CASE statement checks to a boolean value.
• CASE [ expression ]
• WHEN condition_1 THEN result_1
• WHEN condition_2 THEN result_2
• ...
• WHEN condition_n THEN result_n
• ELSE result
• END
Eg
• DECLARE
• grade char(1) := 'A';
• BEGIN
• CASE grade
• when 'A' then dbms_output.put_line('Excellent');
• when 'B' then dbms_output.put_line('Very good');
• when 'C' then dbms_output.put_line('Good');
• when 'D' then dbms_output.put_line('Average');
• when 'F' then dbms_output.put_line('Passed with Grace');
• else dbms_output.put_line('Failed');
• END CASE;
• END;
PL/SQL Loop
• The PL/SQL loops are used to repeat the execution of one or
more statements for specified number of times. These are
also known as iterative control statements.
• LOOP
• Sequence of statements;
• END LOOP;
• Types:
• Basic Loop / Exit Loop
• While Loop
• For Loop
• Cursor For Loop
PL/SQL Exit Loop (Basic Loop)
• PL/SQL exit loop is used when a set of statements is
to be executed at least once before the termination
of the loop. There must be an EXIT condition
specified in the loop, otherwise the loop will get
into an infinite number of iterations. After the
occurrence of EXIT condition, the process exits the
loop.
• LOOP
• Sequence of statements;
• END LOOP;
Example for loop
• DECLARE LOOP
statements;
• i NUMBER := 1; EXIT;
{or EXIT WHEN condition;}
• BEGIN END LOOP;

• LOOP
• EXIT WHEN i>10;
• DBMS_OUTPUT.PUT_LINE(i);
• i := i+1;
• END LOOP;
• END;
PL/SQL While Loop

• PL/SQL while loop is used when a set of


statements has to be executed as long as a
condition is true, the While loop is used. The
condition is decided at the beginning of each
iteration and continues until the condition
becomes false.
• WHILE <condition>
• LOOP statements;
• END LOOP;
Example
• DECLARE
• i INTEGER := 1;
• BEGIN
• WHILE i <= 10 LOOP
• DBMS_OUTPUT.PUT_LINE(i);
• i := i+1;
• END LOOP;
• END;
PL/SQL FOR Loop

• PL/SQL for loop is used when when you want to


execute a set of statements for a predetermined
number of times. The loop is iterated between
the start and end integer values. The counter is
always incremented by 1 and once the counter
reaches the value of end integer, the loop ends.
• FOR counter IN initial_value .. final_value LOOP
• LOOP statements;
• END LOOP;
Eg
• BEGIN
• FOR k IN 1..10 LOOP
• -- note that k was not declared
• DBMS_OUTPUT.PUT_LINE(k);
• END LOOP;
• END;
EXIT statement
• The EXIT statement in PL/SQL programming language has the
following two usages −
• When the EXIT statement is encountered inside a loop, the loop
is immediately terminated and the program control resumes at
the next statement following the loop.
• If you are using nested loops (i.e., one loop inside another
loop), the EXIT statement will stop the execution of the
innermost loop and start executing the next line of code after
the block.
• Syntax
• The syntax for an EXIT statement in PL/SQL is as follows −
• EXIT;
Eg
DECLARE
a number(2) := 10;
BEGIN
LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
EXIT WHEN a > 15;
IF a > 15 THEN
EXIT;
END IF;
END LOOP;
END;
PL/SQL Continue Statement

• The continue statement is used to exit the loop


from the reminder if its body either conditionally
or unconditionally and forces the next iteration of
the loop to take place, skipping any codes in
between.
• For example: If a continue statement exits a cursor
FOR LOOP prematurely then it exits an inner loop
and transfer control to the next iteration of an
outer loop, the cursor closes (in this context,
CONTINUE works like GOTO).
Example
• DECLARE
• x NUMBER := 0;
• BEGIN
• LOOP -- After CONTINUE statement, control resumes here
• DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || TO_CHAR(x));
• x := x + 1;
• IF x < 3 THEN
• CONTINUE;
• END IF;
• DBMS_OUTPUT.PUT_LINE
• ('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
• EXIT WHEN x = 5;
• END LOOP;

• DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || TO_CHAR(x));
• END;
• /
PL/SQL GOTO Statement

• In PL/SQL, GOTO statement makes you able to get an unconditional jump from the
GOTO to a specific executable statement label in the same subprogram of the PL/SQL
block.
• Here the label declaration which contains the label_name encapsulated within the
<< >> symbol and must be followed by at least one statement to execute.

• <<label_name>>
• Statement;
• ..
• ..
• .

• GOTO label_name;
• ..
• ..
Eg
• DECLARE
• a number(2) := 30;
• BEGIN
• <<loopstart>>
• -- while loop execution
• WHILE a < 50 LOOP
• dbms_output.put_line ('value of a: ' || a);
• a := a + 1;
• IF a = 35 THEN
• a := a + 1;
• GOTO loopstart;
• END IF;
• END LOOP;
• END;
Restriction on GOTO statement

• Cannot transfer control into an IF statement,


CASE statement, LOOP statement or sub-block.
• Cannot transfer control from one IF statement
clause to another or from one CASE statement
WHEN clause to another.
• Cannot transfer control from an outer block into
a sub-block.
• Cannot transfer control out of a subprogram.
• Cannot transfer control into an exception handler.
PL/SQL Procedure

• The PL/SQL stored procedure or simply a procedure is a


PL/SQL block which performs one or more specific tasks.
It is just like procedures in other programming languages.
• The procedure contains a header and a body.
• Header: The header contains the name of the procedure
and the parameters or variables passed to the procedure.
• Body: The body contains a declaration section, execution
section and exception section similar to a general PL/SQL
block.
Passing parameters in procedure:

• When you want to create a procedure or function, you have to


define parameters .There is three ways to pass parameters in
procedure:
• IN parameters: The IN parameter can be referenced by the
procedure or function. The value of the parameter cannot be
overwritten by the procedure or the function.
• OUT parameters: The OUT parameter cannot be referenced by
the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
• INOUT parameters: The INOUT parameter can be referenced
by the procedure or function and the value of the parameter
can be overwritten by the procedure or function.
Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Eg
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;

To Execute
EXECUTE greetings;

(OR)
BEGIN
greetings;
END;
Procedure with in & Out
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;
Another Eg
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number)
IS
BEGIN
x := x * x;
END;

BEGIN
a:= 5;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
Procedure Creation Eg
Table Creation
create table user(id number(10) primary key,name varchar2(100));

Procedure Creation
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
/
Calling the procedure
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted success
fully');
END;
/
Drop a procedure
• DROP PROCEDURE procedure_name;
PL/SQL Function

• The PL/SQL Function is very similar to PL/SQL Procedure. The main


difference between procedure and a function is, a function must always
return a value, and on the other hand a procedure may or may not
return a value. Except this, all the other things of PL/SQL procedure are
true for PL/SQL function too.

CREATE [OR REPLACE] FUNCTION function_name [parameters]


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the
parameters.
• IN represents that value will be passed from outside and OUT represents that
this parameter will be used to return a value outside of the procedure.

• The function must contain a return statement.


• RETURN clause specifies that data type you are going to return
from the function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a
standalone function.
Eg
create or replace function adder(n1 in n
umber, n2 in number)
return number
is
n3 number(8);
begin
DECLARE
n3 :=n1+n2;
n3 number(2);
return n3; BEGIN
end; n3 := adder(11,22);
/ dbms_output.put_line('Addition is: ' || n3);

END;
/
• CREATE OR REPLACE FUNCTION welcome_msgJune ( p_name IN VARCHAR2) RETURN VARCHAR2
• IS
• BEGIN
• RETURN (‘Welcome ‘|| p_name);
• END;
• /

• DECLARE
• lv_msg VARCHAR2(250);
• BEGIN
• lv_msg := welcome_msg_func (‘NEC’); dbms_output.put_line(lv_msg);
• END;

• SELECT welcome_msg_func(‘CSE’) FROM DUAL;


Drop a function
• DROP function function_name;
Difference between procedure & function
Procedure Function
•Used mainly to a execute certain process •Used mainly to perform some calculation
•A Function that contains no DML
•Cannot call in SELECT statement statements can be called in SELECT
statement
•Use OUT parameter to return the value •Use RETURN to return the value
•It is not mandatory to return the value •It is mandatory to return the value
•RETURN will simply exit the control from •RETURN will exit the control from
subprogram. subprogram and also returns the value
•Return datatype will not be specified at •Return datatype is mandatory at the time
the time of creation of creation

You might also like