0% found this document useful (0 votes)
75 views26 pages

PL SQL Assertions Triggers

sdfdsfsd

Uploaded by

npuligil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views26 pages

PL SQL Assertions Triggers

sdfdsfsd

Uploaded by

npuligil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

PL/SQL,

Assertions,
Triggers
PL/SQL (procedural language extension to Structured Query Language)
• PL/SQL is to combine database language and procedural programming language.
• The basic unit in PL/SQL is called a block and is made up of three parts:
• a declarative part,
• an executable part and
• an exception-building part.
• PL/SQL enables users to
• Mix SQL statements with procedural constructs,
• It is possible to use PL/SQL blocks and
• Subprograms to group SQL statements before sending them to oracle for
execution.
• Without PL/SQL,
• Oracle must process SQL statements one at a time.
• In a network environment, this can affect traffic flow and slow
down response time.
PL/SQL (procedural language extension to Structured Query Language)
• The PL/SQL blocks can be compiled once and stored in executable form
to improve response time.
• A PL/SQL program that is stored in a database in compiled form and can be
called by name is referred to as a stored procedure.
• A PL/SQL stored procedure that is implicitly started when an INSERT,
UPDATE or DELETE statement is issued against an associated table is
called a trigger.

Disadvantages of SQL:
• SQL doesn’t provide the programmers with a technique of condition
checking, looping and branching.
• SQL statements are passed to Oracle engine one at a time which increases
traffic and decreases speed.
• SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
• PL/SQL is basically a procedural language, which provides the functionality
of decision making, iteration and many more features of procedural
programming languages.
• PL/SQL can execute a number of queries in one block using single command.
• One can create a PL/SQL unit such as procedures, functions, packages,
triggers, and types, which are stored in the database for reuse by
applications.
• PL/SQL provides a feature to handle the exception which occurs in PL/SQL
block known as exception handling block.
• Applications written in PL/SQL are portable to computer hardware or
operating system where Oracle is operational.
• PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:

SQL PL/SQL
SQL is a single query that is used to PL/SQL is a block of codes that used to
perform DML and DDL operations. write the entire program blocks/
procedure/ function, etc.
It is declarative, that defines what PL/SQL is procedural that defines how
needs to be done, rather than how the things needs to be done.
things need to be done.
Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

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
• The basic unit in PL/SQL is a block.
• All PL/SQL programs are made up of blocks, which can be nested
within each other.
• PL/SQL contains 4 main blocks
• Declare
• Begin
• Exception
• End
• Typically, each block performs a logical action in the program. A
block has the following structure:
Structure of PL/SQL

HEADER
Type and Name of block

DECLARE
Variables; Constants; Cursors;

BEGIN

PL/SQL and SQL Statements

EXCEPTION
Exception handlers
END;
PL/SQL BLOCKS
• PL/SQL blocks can be divided into two groups:
1. Named and
2. Anonymous.
• Named blocks are used when creating subroutines.
• These subroutines are procedures, functions, and
packages.
• The subroutines can be stored in the database and referenced
by their names later on.

• Anonymous PL/SQL blocks do not have names.


• As a result, they cannot be stored in the database and
referenced later.
PL/SQL Identifiers
• There are several PL/SQL identifiers such as variables, constants,
procedures, cursors, triggers etc.
• Variables: Like several other programming languages, variables in
PL/SQL must be declared prior to its use.
• They should have a valid name and data type as well.
• Syntax for declaration of variables:
• variable_name data type [NOT NULL := value];
• There are many other data types that can be used like float, int, real,
smallint, long etc.
• It also supports variables used in SQL as well like NUMBER (prec, scale),
varchar, varchar2 etc.
• PL/SQL procedure successfully completed is displayed when the code is
compiled and executed successfully.
• Slash (/) after END;
• The slash (/) tells the SQL*Plus to execute the block.
• Example program to declare variables in PL/SQL :

• SET SERVEROUTPUT ON is used to display the buffer used by the


dbms_output.
• var1 INTEGER is the declaration of variable, named var1 which is of
integer type.
• Assignment operator (:=) : It is used to assign a value to a variable.
PL/SQL EXAMPLE
DECLARE
v_first_name VARCHAR2(35);
v_last_name VARCHAR2(35);
BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123;

DBMS_OUTPUT.PUT_LINE('Student name: '||v_first_name||' '||


v_last_name);

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
('There is no student with student id 123');
END;
DISPLAYING OUTPUT
• The outputs are displayed by using DBMS_OUTPUT which is a built-in
package that enables the user to display output, debugging
information, and send messages from PL/SQL blocks, subprograms,
packages, and triggers.
• Let us see an example to see how to display a message using PL/SQL:

dbms_output.put_line
• command is used to direct the
PL/SQL output to a screen.
USING COMMENTS
• Like in many other programming languages, in PL/SQL also, comments
can be put within the code which has no effect in the code.
• There are two syntaxes to create comments in PL/SQL:
• Single Line Comment: To create a single line comment,
• the symbol – – is used.
• Multi Line Comment: To create comments that span over several lines,
the symbol /* and */ is used.
TAKING INPUT FROM USER
• Just like in other programming languages, in PL/SQL also, we can take
input from the user and store it in a variable.
• Example : code to print sum of two numbers taken from the user.
EXAMPLE
BEGIN
DBMS_OUTPUT.PUT_LINE('Today is ‘||’&sv_day');
DBMS_OUTPUT.PUT_LINE('Tomorrow will be ‘||’ &sv_day');
END;
This example produces the following output:

Enter value for sv_day: Monday


old 2: DBMS_OUTPUT.PUT_LINE('Today is ‘||’ &sv_day');
new 2: DBMS_OUTPUT.PUT_LINE('Today is ‘||’ Monday');
Enter value for sv_day: Tuesday
old 3: DBMS_OUTPUT.PUT_LINE('Tomorrow will be ‘||’ &sv_day');
new 3: DBMS_OUTPUT.PUT_LINE('Tomorrow will be ‘||’ Tuesday');
Today is Monday
Tomorrow will be Tuesday
PL/SQL procedure successfully completed.
Control Structures
DECLARE
Conditional Control (IF-THEN-ELSE) acct_balance NUMBER(11,2);
The IF-THEN-ELSE statement lets acct CONSTANT NUMBER(4) := 3;
you execute a sequence of debit_amt CONSTANT NUMBER(5,2) := 500.00;
statements conditionally. The IF BEGIN
clause checks a condition; the THEN SELECT bal INTO acct_balance FROM accounts
clause defines what to do if the WHERE account_id = acct
condition is true; the ELSE clause FOR UPDATE OF bal;
defines what to do if the condition is
false or null. IF acct_balance >= debit_amt THEN
Consider the program below, which UPDATE accounts SET bal = bal - debit_amt
processes a bank transaction. WHERE account_id = acct;
Before allowing you to withdraw ELSE
$500 from account 3, it makes sure INSERT INTO temp VALUES
the account has sufficient funds to (acct, acct_balance, 'Insufficient funds');
cover the withdrawal. If the funds are -- insert account, current balance, and message
available, the program debits the END IF;
account; otherwise, the program COMMIT;
inserts a record into an audit table. END;
Control Structures
Iterative Control (LOOP)
LOOP statements let you execute a sequence of statements multiple times.
You place the keyword LOOP before the first statement in the sequence
and the keywords END LOOP after the last statement in the sequence.
For example:
LOOP
EXIT WHEN i > 100;
END LOOP;
Iterative Control (FOR-LOOP)
The FOR-LOOP statement lets you specify a range of integers, then
execute a sequence of statements once for each integer in the range. For
example:
FOR i IN 1..order_qty LOOP
UPDATE sales SET custno = customer_id
WHERE serial_num = serial_num_seq.NEXTVAL;
END LOOP;
Control Structures
Iterative Control (WHILE-LOOP)
The WHILE-LOOP statement associates a condition with a
sequence of statements. Before each iteration of the loop,
the condition is evaluated. If TRUE, loop continues. If FALSE
the loop ends and control passes to the next statement.
For example:
WHILE salary < 4000 LOOP
SELECT sal, mgr, ename
INTO salary, mgr_num, last_name
FROM emp WHERE empno = mgr_num;
END LOOP;
Control Structures
Sequential Control
The GOTO statement lets you branch to a label unconditionally. The label, an undeclared
identifier enclosed by double angle brackets, must precede an executable statement or a
PL/SQL block.
POOR PROGRAMMING PRACTICE! Avoid using GOTO!!
Example:
IF rating > 90 THEN
GOTO calc_raise; -- branch to label
END IF;
...
<<calc_raise>>
IF job_title = 'SALESMAN' THEN -- control resumes here
amount := commission * 0.25;
ELSE
amount := salary * 0.10;
END IF;
PL/SQL Cursors
Cursors
Oracle uses work areas (cursors) to execute SQL statements and store processing
information.
There are two kinds of cursors:
• Implicit Cursors: PL/SQL implicitly declares a cursor for all SQL data manipulation

statements, including queries that return only one row.


• Explicit Cursors: For queries that return more than one row, you can explicitly declare a

cursor to process the rows individually. Example:


DECLARE
CURSOR c1 IS
SELECT empno, ename, job
FROM emp WHERE deptno = 20;

The set of rows returned by a multi-row query is called the result set. An explicit cursor
"points" to the current row in the result set. This allows your program to process the
rows one at a time.
PL/SQL Cursors
Manipulating Cursors
You use the OPEN, FETCH, and CLOSE statements to control a cursor. The OPEN
statement executes the query associated with the cursor, identifies the result set, and
positions the cursor before the first row. The FETCH statement retrieves the current row
and advances the cursor to the next row. When the last row has been processed, the
CLOSE statement disables the cursor.

Cursor FOR Loops


In most situations that require an explicit cursor, you can simplify coding by using a cursor
FOR loop instead of the OPEN, FETCH, and CLOSE statements.
DECLARE
CURSOR c1 IS
SELECT ename, sal, hiredate, deptno FROM emp;
...
BEGIN
FOR emp_rec IN c1 LOOP
...
salary_total := salary_total + emp_rec.sal;
END LOOP;
END;
Attributes
Attributes
PL/SQL variables and cursors have attributes, Database columns and tables have similar
attributes, which you can use to ease maintenance.
%TYPE
The %TYPE attribute provides the datatype of a variable or database column. Example:
my_title books.title%TYPE;
Declaring my_title with %TYPE has two advantages. First, you need not know the exact
datatype of title. Second, if you change the database definition of title, the datatype of
my_title changes accordingly at run time.
%ROWTYPE
In PL/SQL, records are used to group data. The %ROWTYPE attribute provides a record
type that represents a row in a table. The record can store an entire row of data selected
from the table or fetched from a cursor or cursor variable.
Columns in a row and corresponding fields in a record have the same names and data
types.
Example:
DECLARE
dept_rec dept%ROWTYPE; -- declare record var.
You use dot notation to reference fields.
Example:
my_deptno := dept_rec.deptno;
Procedures and Packages
Modularity
Modularity lets you break an application down into manageable, well-defined logic
modules. Besides blocks and subprograms, PL/SQL provides the package, which allows
you to group related program objects into larger units.
Subprograms
PL/SQL has two types of subprograms called procedures and functions, which can take
parameters and be invoked (called). A subprogram is like a miniature program, beginning
with a header followed by an optional declarative part, an executable part, and an
optional exception-handling part.
Packages
PL/SQL lets you bundle logically related types, program objects, and subprograms into a
package. Each package is easy to understand and the interfaces between packages are
simple, clear, and well defined. This aids application development.
Packages usually have two parts: a specification and a body. The specification is the
interface to your applications; it declares the types, constants, variables, exceptions,
cursors, and subprograms available for use. The body defines cursors and subprograms
and so implements the specification.
Only the declarations in the package specification are visible and accessible to
applications. Implementation details in the package body are hidden and inaccessible.
Packages can be compiled and stored in an Oracle database, .... When you call a
packaged subprogram for the first time, the whole package is loaded into memory.
Error Handling
Error Handling
PL/SQL makes it easy to detect and process predefined
and user-defined error conditions called exceptions.
When an error occurs, an exception is raised. Normal
execution stops and control transfers to the exception-
handling part of your PL/SQL block or subprogram. To
handle raised exceptions, you write separate routines
called exception handlers.
Predefined exceptions are raised implicitly by the runtime
system.
You must raise user-defined exceptions explicitly with the
RAISE statement.
Error Handling
You can define exceptions of your own in the declarative part of any PL/SQL block or
subprogram. In the executable part, you check for the condition that needs special
attention. If you find that the condition exists, you execute a RAISE statement. Example:
DECLARE
salary NUMBER(7,2);
commission NUMBER(7,2);
comm_missing EXCEPTION; -- declare exception
BEGIN
SELECT sal, comm INTO salary, commission FROM emp
WHERE empno = :emp_id;
IF commission IS NULL THEN
RAISE comm_missing; -- raise exception
ELSE
:bonus := (salary * 0.05) + (commission * 0.15);
END IF;
EXCEPTION -- begin exception handlers
WHEN comm_missing THEN
-- process error
END;

You might also like