DMA Chapter No4
DMA Chapter No4
DMA Chapter No4
• PL/SQL Introduction
SQL is a single query that is used to perform DML and DDL PL/SQL is a block of codes that used to write the entire
operations. program blocks/ procedure/ function, etc.
It is declarative, that defines what needs to be done, rather PL/SQL is procedural that defines how the things needs to be
than how things need to be done. done.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it.
Structure of PL/SQL Block:
• DECLARE
• declaration statements;
• BEGIN
• executable statements
• EXCEPTIONS
• exception handling statements
• END;
• Declare section starts with DECLARE keyword in which variables,
constants, records as cursors can be declared which stores data
temporarily. It basically consists definition of PL/SQL identifiers.
This part of the code is optional.
• Execution section starts with BEGIN and ends
with END keyword.This is a mandatory section and here the
program logic is written to perform any task like loops and
conditional statements. It supports all DML commands, DDL
commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword.This section is
optional which contains statements that are executed when a
run-time error occurs. Any exceptions can be handled in this
section.
PL/SQL Scalar Data
• 1Numeric
• Numeric values on which arithmetic operations are performed.
• 2Character
• Alphanumeric values that represent single characters or strings of characters.
• 3Boolean
• Logical values on which logical operations are performed.
• 4Datetime
• Dates and times.
PL/SQL Numeric Data
• 2BINARY_INTEGER
• Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
• 3BINARY_FLOAT
• Single-precision IEEE 754-format floating-point number
• 4BINARY_DOUBLE
• Double-precision IEEE 754-format floating-point number
• 5NUMBER(prec, scale)
• Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable
can also represent 0
• 7DECIMAL(prec, scale)
• IBM specific fixed-point type with maximum precision of 38 decimal digits
• 8NUMERIC(pre, secale)
• Floating type with maximum precision of 38 decimal digits
• 9DOUBLE PRECISION
• ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)
• 10FLOAT
• ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)
• 11INT
• ANSI specific integer type with maximum precision of 38 decimal digits
• 12INTEGER
• ANSI and IBM specific integer type with maximum precision of 38 decimal digits
• 14REAL
• Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)
PL/SQL Character Data Types
• 1CHAR
• Fixed-length character string with maximum size of 32,767 bytes
• 2VARCHAR2
• Variable-length character string with maximum size of 32,767 bytes
• 3RAW
• Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL
• 4NCHAR
• Fixed-length national character string with maximum size of 32,767 bytes
• 5NVARCHAR2
• Variable-length national character string with maximum size of 32,767 bytes
• 6LONG
• Variable-length character string with maximum size of 32,760 bytes
• 7LONG RAW
• Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL
• 8
PL/SQL Variables
• Following are some important rules to keep in mind while defining and
using a variable in PL/SQL:
• A variable name is user-defined. It should begin with a character and can be
followed by maximum of 29 characters.
• Keywords (i.e, reserved words ) of PL/SQL cannot be used as variable name.
• Multiple variables can be declared in a single line provided they must be
separated from each other by at least one space and comma.For eg: a,b,c
int;
• Variable names containing two words should not contain space between
them. It must be covered by underscore instead.For eg: Roll_no
• A variable name is case sensitive, which means a_var is not same as A_var
• set serveroutput on;
• DECLARE
• a NUMBER(2);
• b NUMBER(2) := 5;
• BEGIN a := b;
• dbms_output.put_line(a);
• END;
PL/SQL Constants
• Constants are those values which when declared
remain fixed throughout the PL/SQL block. For
declaring constants, a constant keyword is used.
• Syntax for declaring constants:
• Constant_Name constant Datatype(size) := value;
• Let's take a simple code example,
• school_name constant VARCHAR2(20) := "DPS";
• In the above code example, constant name is user
defined followed by a keyword constant and then
we have declared its value, which once declared
cannot be changed.
PL/SQL Control Statements
• IF THEN
• IF THEN ELSE
• IF THEN ELSIF
• CASE
IF THEN Statement
• The IF THEN statement either runs or skips a sequence of one or more statements,
depending on a condition.
• SYNTAX:
• IF condition THEN
statements
• END IF;
• If the condition is true, the statements run; otherwise, the IF statement does nothing.
END IF;
IF ELSE IFLSE
• DECLARE
PROCEDURE p (
sales NUMBER,
quota NUMBER,
emp_id NUMBER )
IS bonus NUMBER := 0;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
ELSE IF sales > quota THEN
bonus := 50;
ELSE bonus := 0;
END IF;
END IF;
Iterative Statements in PL/SQL
• EXCEPTION
• WHEN no_data_found THEN
• dbms_output.put_line('No such customer!');
• WHEN others THEN
• dbms_output.put_line('Error!');
• END;
• /
User-defined Exceptions
• DECLARE
• my-exception EXCEPTION;
DECLARE
c_id customers.id%type := &c_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
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;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
cursor
• Oracle creates a memory area, known as the context area, for processing an
SQL statement, which contains all the information needed for processing the
statement; for example, the number of rows processed, etc.
• A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement. The set of rows the cursor holds is referred to as the active set.
• Implicit cursors
• Explicit cursors
Implicit cursors
• Implicit cursors are automatically created by Oracle
whenever an SQL statement is executed.
• Whenever a DML statement (INSERT, UPDATE and
DELETE) is issued, an implicit cursor is associated
with this statement. For INSERT operations, the
cursor holds the data that needs to be inserted. For
UPDATE and DELETE operations, the cursor identifies
the rows that would be affected.
Attribute
S.No Attribute & Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
1
rows or a SELECT INTO statement returned one or more rows. Otherwise, it
returns FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
2
DELETE statement affected no rows, or a SELECT INTO statement returned no
rows. Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
• DECLARE
• total_rows number(2);
• BEGIN
• UPDATE customers SET salary = salary + 500;
• IF sql%notfound THEN
• dbms_output.put_line('no customers selected');
• ELSIF sql%found THEN
• total_rows := sql%rowcount;
• dbms_output.put_line( total_rows || ' customers selected ');
• END IF;
• END;
• /
Explicit Cursors
• Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is
used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements,
such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a
table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only
for row-level triggers.
• CREATE OR REPLACE TRIGGER display_salary_changes BEFORE
DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW
WHEN (ID > 0)
• DECLARE
• sal_diff number;
• BEGIN
• sal_diff := :NEW.salary - :OLD.salary;
• dbms_output.put_line('Old salary: ' || :OLD.salary);
• dbms_output.put_line('New salary: ' || :NEW.salary);
• dbms_output.put_line('Salary difference: ' || sal_diff);
• END;
PL/SQL - Procedures
• BEGIN
• a:= 23;
• b:= 45;
• c := findMax(a, b);
• dbms_output.put_line(' Maximum of (23,45): ' || c);
• END;