Lecture-16 - Advance-SQL PL-SQL
Lecture-16 - Advance-SQL PL-SQL
introduction
PL/SQL
• PL/SQL stands for “Procedural Language extensions to the Structured
Query Language”. SQL is a popular language for both querying and
updating data in the relational database management systems
(RDBMS). PL/SQL adds many procedural constructs to SQL language
to overcome some limitations of SQL. Besides, PL/SQL provides a
more comprehensive programming language solution for building
mission-critical applications on Oracle Databases.
Introduction to PL/SQL data types
• Exception-handling section
A PL/SQL block has an exception-handling section that starts with the keyword EXCEPTION. The
exception-handling section is where you catch and handle exceptions raised by the code in the execution
section.
• Note a block itself is an executable statement, therefore you can nest a block within other blocks.
Anonymous Block
• PL/SQL anonymous block example
• The following example shows a simple PL/SQL anonymous block with
one executable section.
• BEGIN
• DBMS_OUTPUT.put_line ('Hello World!');
• END;
• The executable section calls the DMBS_OUTPUT.PUT_LINE procedure
to display the "Hello World" message on the screen.
Execute a PL/SQL
anonymous block using
SQL*Plus
Execute a PL/SQL anonymous block using SQL Developer
Declaring variables
• The syntax for a variable declaration is as follows:
• variable_name datatype [NOT NULL] [:= initial_value];
Declaring variable (Cont.)
• By convention, local variable names should start with l_ and global variable names should have a
prefix of g_ .
• The following example declares three variables l_total_sales, l_credit_limit, and l_contact_name:
DECLARE
l_total_sales NUMBER(15,2);
l_credit_limit NUMBER (10,0);
l_contact_name VARCHAR2(255);
BEGIN
NULL;
END;
Default values
• PL/SQL allows you to set a default value for a variable at the declaration time. To assign a
default value to a variable, you use the assignment operator (:=) or the DEFAULT keyword.
• The following example declares a variable named l_product_name with an initial value ‘La
DECLARE
l_product_name VARCHAR2( 100 ) := 'Laptop';
BEGIN
NULL;
END;
ptop':
• It is equivalent to the following block:
• DECLARE
• l_product_name VARCHAR2( 100 ) DEFAULT 'Laptop';
• BEGIN
• NULL;
• END;
NOT NULL constraint
• If you impose the NOT NULL constraint on a value, then the variable
cannot accept a NULL value. Besides, a variable declared with the
NOT NULL must be initialized with a non-null value.
DECLARE
l_shipping_status VARCHAR2( 25 ) NOT NULL := 'Shipped';
BEGIN
l_shipping_status := '';
END;
PL/SQL issued the following error:
ORA-06502: PL/SQL: numeric or value error
Anchored declarations
1 DECLARE
2 l_customer_name customers.name%TYPE;
3 l_credit_limit customers.credit_limit%TYPE;
4 BEGIN
5 SELECT
6 name, credit_limit
7 INTO
8 l_customer_name, l_credit_limit
9 FROM
10 customers
11 WHERE
12 customer_id = 38;
13
14 DBMS_OUTPUT.PUT_LINE(l_customer_name || ':' || l_credit_limit );
15 END;
16 /