Intro
Intro
• PL/SQL engine separates PL/SQL units and SQL part in the input.
• The SQL part will be sent to database server where the actual
interaction with database takes place.
• Since the PL/SQL expects the executable statements from this block
this cannot be an empty block, i.e., it should have at least one valid
executable code line in it.
• This is the section where the exception raised in the execution block is
handled.
• Control from this section can never return to the execution block.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
• The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
• The END; line signals the end of the PL/SQL block. To run the
code from the SQL command line, you may need to type / at the
beginning of the first blank line after the last line of the code.
• Static SQL supports DML operations and transaction control from PL/SQL block.
• PL/SQL allows sending an entire block of statements to the database at one time.
This reduces network traffic and provides high performance for the applications.
Hello World
PL/SQL procedure successfully completed.
PL/SQL - Data Types
Scalar
1 Single values with no internal components, such as a NUMBER, DATE, or
BOOLEAN.
Composite
3 Data items that have internal components that can be accessed individually.
For example, collections and records.
Reference
4
Pointers to other data items.
PL/SQL Large Object (LOB) Data Types
Large Object (LOB) data types refer to large data items such as text, graphic
images, video clips,and sound waveforms.
• For example −
sales number(10, 2);
name varchar2(25);
address varchar2(100);
Initializing Variables in PL/SQL
• Whenever you declare a variable, PL/SQL assigns it a default
value of NULL.
• For example −
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
• You can also specify that a variable should not
have a NULL value using the NOT NULL
constraint.
Value of c: 30
Value of f: 23.433333333333333333
• For example, you want to keep track of your books in a library. You
might want to track the following attributes about each book, such as
Title, Author, Subject, Book ID.
BEGIN
SELECT * into customer_rec
FROM customers WHERE id = 5;
END;
/
• When the above code is executed at the SQL prompt, it
produces the following result −
Customer ID: 5
Customer Name: Hardik
Customer Address: Bhopal
Customer Salary: 9000
PL/SQL procedure successfully completed.
Cursor-Based Records
• The following example illustrates the concept of cursor-based records.
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' ||
customer_rec.name);
END LOOP;
END; /
• Output
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal
IF CONDITION
THEN
STATEMENT 1;
…
STATEMENT N;
END IF;
IF CONDITION 1
THEN
STATEMENT 1;
ELSIF CONDITION 2
THEN
STATEMENT 2;
ELSIF CONDITION 3
THEN
STATEMENT 3;
…
ELSE
STATEMENT N;
END IF;
ELSIF STATEMENTS
• Output
Enter value for sv_num: 5
old 2: v_num NUMBER := &sv_num;
new 2: v_num NUMBER := 5;
5 is a positive number
PL/SQL procedure successfully completed.
ELSIF STATEMENTS
DECLARE
v_num NUMBER := &sv_num;
BEGIN
IF v_num < 0
THEN
DBMS_OUTPUT.PUT_LINE (v_num||' is a negative
number');
ELSIF v_num > 0
THEN
DBMS_OUTPUT.PUT_LINE (v_num||' is a positive
number');
END IF;
DBMS_OUTPUT.PUT_LINE ('Done…');
END;
NESTED IF STATEMENTS
DBMS_OUTPUT.PUT_LINE('This is a number');
ELSE
DBMS_OUTPUT.PUT_LINE('This is not a number');
END IF;
END IF;
END;
Example explained
• In the example above, the condition
(v_letter >= 'A' AND v_letter <= 'Z')
OR (v_letter >= 'a' AND v_letter <= 'z')
uses logical operators AND and OR.
• Syntax
• The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
CONTINUE
• This keyword sends an instruction to the PL/SQL engine that
whenever PL/SQL engine encounters this keyword inside the
loop, then it will skip the remaining code in the execution block of
the code, and next iteration will start immediately. This will be
mainly used if the code inside the loop wants to be skipped for
certain iteration values.
EXIT / EXIT WHEN
• This keyword sends an instruction to the PL/SQL engine
that whenever PL/SQL engine encounters this keyword,
then it will immediately exit from the current loop.
• After the body of the for loop executes, the value of the counter
variable is increased or decreased.
• In such case, iteration proceeds the other way. After each iteration, the loop counter
is decremented.
• However, you must write the range bounds in ascending (not descending) order.
DECLARE a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20
LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
• value of a: 20
• value of a: 19
• value of a: 18
• value of a: 17
• value of a: 16
• value of a: 15
• value of a: 14
• value of a: 13
• value of a: 12
• value of a: 11
• value of a: 10
• Example
• The program asks for a customer ID, when the user enters
an invalid ID, the exception invalid_id is raised.
DECLARE EXCEPTION
c_id customers.id%type := &cc_id; WHEN ex_invalid_id THEN
c_name customers.name%type; dbms_output.put_line('ID must be
c_addr customers.address%type; -- user greater than zero!');
defined exception WHEN no_data_foundTHEN
ex_invalid_id EXCEPTION; dbms_output.put_line('No such
BEGIN customer!');
IF c_id <= 0 THEN WHEN others THEN
RAISE ex_invalid_id; dbms_output.put_line('Error!'); END;
ELSE /
SELECT name, address INTO
c_name, c_addr FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE
('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE
('Address: ' || c_addr);
END IF;
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
• Syntax:-
• CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
• Where,
• procedure-name specifies the name of the procedure.
• [OR REPLACE] option allows the modification of an
existing procedure.
• The optional parameter list contains name, mode and
types of the parameters.
• IN represents the value that will be passed from outside
and OUT represents the parameter that will be used to
return a value outside of the procedure.
• procedure-body contains the executable part.
• IS keyword is used, when the procedure is nested into
some other blocks.
• The AS keyword is used instead of the IS keyword for
creating a standalone procedure.
• Example
• The following example creates a simple procedure that displays the
string 'Hello World!' on the screen when executed.
• When the above code is executed using the SQL prompt, it will
produce the following result −
• Procedure created.
Executing a Standalone Procedure
• A standalone procedure can be called in two ways −
• Using the EXECUTE keyword
• Calling the name of the procedure from a PL/SQL block
• The above procedure named 'greetings' can be called with the EXECUTE
keyword as −
EXECUTE greetings;
• The above call will display −
Hello World
PL/SQL procedure successfully completed.
• The procedure can also be called from another PL/SQL block −
BEGIN
greetings;
END;
/
• The above call will display −
Hello World
PL/SQL procedure successfully completed.
• Deleting a Standalone Procedure
• A standalone procedure is deleted with the
DROP PROCEDURE statement.
OUT
An OUT parameter returns a value to the calling program. Used for
getting output from the subprograms. Inside the subprogram, an OUT
parameter acts like a variable. You can change its value and reference
the value after assigning it. The actual parameter must be variable
and it is passed by value.
IN OUT
• An IN OUT parameter passes an initial value to a
subprogram and returns an updated value to the caller. It
can be assigned a value and the value can be read.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
• Output
• Square of (23): 529
• PL/SQL procedure successfully completed.
Methods for Passing Parameters
• Actual parameters can be passed in three ways −
Positional notation:-findMin(a, b, c, d);
• Output:-
Function created.
Calling a Function
• While creating a function, you give a definition of what the
function has to do.
• To use a function, you will have to call that function to perform
the defined task.
• When a program calls a function, the program control is
transferred to the called function.
• A called function performs the defined task and when its return
statement is executed or when the last end statement is reached,
it returns the program control back to the main program.
• To call a function, you simply need to pass the required
parameters along with the function name and if the function
returns a value, then you can store the returned value.
• Following program calls the function totalCustomers from an
anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
• Output:-
• Total no. of Customers: 6
• PL/SQL procedure successfully completed.