Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

PL SQL Basics

Uploaded by

ATR LYNX
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PL SQL Basics

Uploaded by

ATR LYNX
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

PL/SQL Basics

Objectives
• At the end of this session, you will be able to:

– Understand the features of PL/SQL


– Comprehend the PL/SQL Block terminology
– Recognize various PL/SQL types, variables and
constants
– Use SELECT statement inside PL/SQL Block
– Manipulate data through a PL/SQL Block
– Write various PL/SQL control structures
– Write interactive PL/SQL Blocks
CONFIDENTIAL© Copyright 2008 Tech
2
Mahindra Limited
Agenda
• PL/SQL block structure
• Data types and variables
• Select statement in a PL/SQL block
• DML statement in a PL/SQL block
• Control structures

CONFIDENTIAL© Copyright 2008 Tech


3
Mahindra Limited
Need for PL/SQL
• SQL being a 4GL can allow only customized operations related to
data, like data design, data manipulation, data retrieval and data
control. SQL has no provision for implementing application specific
functionalities.
• A procedural language was introduced by Oracle to enable users to
write application-specific SQL oriented programs.
• Procedural Language/SQL, extends SQL by adding constructs found
in other procedural languages, such as:
– Variables and data types
– Control structures such as IF-THEN-ELSE statement and Loops
– Procedures and Functions
– Object types and Methods
• It combines the power and flexibility of SQL with the programming
constructs available in 3GLs

4
Need for PL/SQL (Contd.)
• PL/SQL improves the performance when multiple
SQL statements are to be executed.
– Without PL/SQL, Oracle must process SQL statements
one at a time.
– Programs that issue many SQL statements require
multiple calls to the database, resulting in significant
network and performance overhead.
– With PL/SQL, an entire block of statements can be
sent to Oracle at one time. This can drastically reduce
network traffic between the database and an
application.
CONFIDENTIAL© Copyright 2008 Tech
5
Mahindra Limited
PL/SQL Improves Performance

CONFIDENTIAL© Copyright 2008 Tech


6
Mahindra Limited
Advantages of PL/SQL
• Tight Integration with SQL
• Better Performance
• Higher Productivity
• Full Portability
• Tight Security
• Access to Pre-defined Packages
• Support for Object-Oriented Programming
• Support for Developing Web Applications and
Pages
CONFIDENTIAL© Copyright 2008 Tech
7
Mahindra Limited
PL/SQL Block
• PL/SQL is a block structured language
• It is composed of one or more blocks
• Types of Blocks
– Anonymous Blocks: constructed dynamically and
executed only once
– Named Blocks: Subprograms, Triggers, etc.
• Subprograms: are named PL/SQL blocks that are stored in
the database and can be invoked explicitly as and when
required; e.g. Procedures, Functions and Packages
• Triggers: are named blocks that are also stored in the
database; Invoked implicitly whenever the triggering event
occurs; e.g. Database Triggers

CONFIDENTIAL© Copyright 2008 Tech


8
Mahindra Limited
PL/SQL Block Structure
• A PL/SQL block has the following structure

DECLARE
Variables, cursors, user-defined
exceptions, etc.

BEGIN

SQL and PL/SQL statements

EXCEPTION

Trapping Errors occurred in executable


section

END;

Note: BEGIN & END are compulsory statements

CONFIDENTIAL© Copyright 2008 Tech


9
Mahindra Limited
PL/SQL Block Structure
• PL/SQL Block consists of three sections

– Declarative: Contains declarations of variables,


constants, cursors, user-defined exceptions and types
(Optional)
– Executable: Contains SQL statements to manipulate
data in the database and PL/SQL statements to
manipulate data in the block
– Exception Handling: Specifies the actions to perform
when errors and abnormal conditions arise in the
executable section (Optional)
CONFIDENTIAL© Copyright 2008 Tech
10
Mahindra Limited
PL/SQL Data Types
• The PL/SQL data types are divided into

– Scalar Types: used to hold a single value; e.g. DATE,


VARCHAR2, NUMBER etc.
– Composite Types: used to hold one or more items of
the same or dissimilar types; e.g. PL/SQL Records
– Reference Types: Similar to Pointers in C; e.g. REF
Cursor
– Large Objects (LOB): A large object can be either a
binary or character value up to 4GB; e.g. BLOB, CLOB,
NCLOB and BFILE

CONFIDENTIAL© Copyright 2008 Tech


11
Mahindra Limited
PL/SQL Data Types

CONFIDENTIAL© Copyright 2008 Tech


12
Mahindra Limited
PL/SQL Variables
• Declaration Syntax
identifier [CONSTANT] datatype [NOT NULL] [:= expr | DEFAULT expr]
Note: Square brace indicates optional
• Valid variable declarations
DECLARE
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := ’Atlanta’;
c_comm CONSTANT NUMBER := 1400;
v_NoOfSeats NUMBER DEFAULT 45;
v_FirstName VARCHAR2(20) DEFAULT ‘SCOTT’
• Invalid variable Declarations
v_deptno number(2) NOT NULL;
v_name varchar2 DEFAULT ‘Sachin’;
• Inheriting data type
You can declare variables to inherit the data type of a database column or other variable
v_empno emp.empno%TYPE ;

CONFIDENTIAL© Copyright 2008 Tech


13
Mahindra Limited
PL/SQL Variables (Contd.)
• Constants: using the CONSTANT keyword we can
declare a constant
c_max_size CONSTANT NUMBER := 100;

• Bind Variable: a variable declared in a host


environment and used in many blocks by referencing it
with “:” prefix

• Row Type Variable: holds one record/row at a time


e.g. v_record emp%ROWTYPE;

CONFIDENTIAL© Copyright 2008 Tech


14
Mahindra Limited
PL/SQL Variables (Contd.)
• PL/SQL Record type Variable: A record is a group of
related data items stored in fields, each with its own
name and data type
• A record containing a field for each item lets you
treat the data as a logical unit
• The variable based on a PL/SQL record type is a
composite data member having fields as defined in
the corresponding record type
• Syntax:
TYPE type_name IS RECORD
(field_declaration[,field_declaration]...);
variable_name type_name;
• Example:
-- Type declaration
TYPE DeptRec IS RECORD (
dept_id dept.deptno%TYPE,
dept_name VARCHAR2(14),
dept_loc VARCHAR2(13)
);
-- Record type CONFIDENTIAL©
variableCopyright
declaration
2008 Tech
vDeptRec DeptRec; 15
Mahindra Limited
Guidelines for Declaring PL/SQL Variables

• Follow the naming conventions

• Initialize variables designated as NOT NULL and CONSTANT

• Declare one identifier per line

• Initialize identifiers by using the assignment operator (:=) or the reserved word
“DEFAULT”

CONFIDENTIAL© Copyright 2008 Tech


16
Mahindra Limited
Operators in PL/SQL
• Arithmetic Operators
*, /, +, -, ^
• Comparison Operators
>, < , >= , <= , <> , = , IN , BETWEEN, LIKE, IS
• Logical Operators
NOT, AND, OR
• Other Operators
.. , **, ||
CONFIDENTIAL© Copyright 2008 Tech
17
Mahindra Limited
Comments in PL/SQL
• To comment line or lines in a PL/SQL program
use,

– -- for single line comment


– /* */ for multi-line comment

CONFIDENTIAL© Copyright 2008 Tech


18
Mahindra Limited
SQL Functions in PL/SQL
• Available in procedural statements
– Single-row number and character functions
– Data type conversion functions
– Date functions
• Not available in procedural statements
– Decode Function
– Group Functions (Directly)
• Valid use of functions in a PL/SQL block:
v_name := UPPER(‘ketan’);
v_date := TO_DATE(’12,February 1998’,’DD,Month YYYY’);

• Invalid use of functions in a PL/SQL block:


v_tot_sal := SUM(sal);
v_grade := DECODE(job,’MANAGER’,’A’,’CLERK’,’B’,’C’);

CONFIDENTIAL© Copyright 2008 Tech


19
Mahindra Limited
Displaying Information from a PL/SQL Block

• Use DBMS_OUTPUT.PUT_LINE.

• DBMS_OUTPUT is a package PUT_LINE is a procedure within that package

• Displays a message, value of a variable or both on to the screen


– Example 1:
• DBMS_OUTPUT.PUT_LINE(‘Hello! Welcome to PL/SQL’);
– Example 2:
• v_ename := ‘Amit’;
• -- where v_name is a local variable declared in the block
• DBMS_OUTPUT.PUT_LINE(‘Employee Name is :’ || v_ename);

• Note: The DBMS_OUTPUT package must be enabled before using it by executing


SQL *Plus command SET SERVEROUTPUT ON

CONFIDENTIAL© Copyright 2008 Tech


20
Mahindra Limited
First PL/SQL Program
DECLARE

X NUMBER(3) := 10;
Y NUMBER(3) := 20;

BEGIN

DBMS_OUTPUT.PUT_LINE(‘Welcome to PL/SQL Programming’);


DBMS_OUTPUT.PUT_LINE(‘The value of variable X is : ‘
|| X);
DBMS_OUTPUT.PUT_LINE(‘The value of variable Y is : ‘
|| Y);

END;

CONFIDENTIAL© Copyright 2008 Tech


21
Mahindra Limited
Nested Blocks
• A block within a block called as a Nested Block

CONFIDENTIAL© Copyright 2008 Tech


22
Mahindra Limited
Example: Labeled Nested Block

-- Outer Block Starts here


<<l_outer>> -- Label given to the outer block
DECLARE
v_empname VARCHAR2(20) := 'Neeta';
v_salary NUMBER(4) := 1000;
BEGIN
DECLARE -- Inner Block Starts Here
v_empname VARCHAR2(30) :='Richa';
v_address VARCHAR2(20) := 'Pune';
BEGIN
DBMS_OUTPUT.PUT_LINE(l_outer.v_empname);
DBMS_OUTPUT.PUT_LINE (v_empname);
END; -- Inner block ends
DBMS_OUTPUT.PUT_LINE (v_empname);
DBMS_OUTPUT.PUT_LINE (v_salary);
END; -- Outer Block Ends
/

CONFIDENTIAL© Copyright 2008 Tech


23
Mahindra Limited
SQL Statements in PL/SQL
• Valid SQL statements inside PL/SQL Block
– SELECT statement
– All DML statements
– Transaction statements like COMMIT & ROLLBACK
• SELECT statement inside PL/SQL Block
– To use the SELECT statement, the INTO clause is mandatory
– Select statements must return a single row
– Returning no row or multiple rows, both, generate an error
– Syntax: SELECT column_list INTO variable/s
FROM table_name WHERE condition;

CONFIDENTIAL© Copyright 2008 Tech


24
Mahindra Limited
SELECT Statement inside PL/SQL Block
DECLARE
v_empno emp.empno%TYPE := &empno;
v_ename emp.ename%TYPE;
BEGIN
SELECT ename INTO v_ename
FROM emp WHERE empno=v_empno;
DBMS_OUTPUT.PUT_LINE(' The name is : '||
v_ename);
END;
/

CONFIDENTIAL© Copyright 2008 Tech


25
Mahindra Limited
%ROWTYPE Variable Example
DECLARE
v_dno dept.deptno%TYPE := &dno;
deptRec dept%ROWTYPE;
BEGIN
SELECT deptno,dname,loc INTO deptRec
FROM dept WHERE deptno=v_dno;
DBMS_OUTPUT.PUT_LINE(deptRec.deptno);
DBMS_OUTPUT.PUT_LINE(deptRec.dname);
DBMS_OUTPUT.PUT_LINE(deptRec.loc);
END;
/

CONFIDENTIAL© Copyright 2008 Tech


26
Mahindra Limited
Bind Variable Example The variable is declared at session level
outside the block. To refer to this
VARIABLE result NUMBER
environment variable in the PL/SQL block
we have to use colon sign

BEGIN
SELECT (sal*12)+nvl(comm,0) INTO :result FROM emp WHERE
empno=7839;
DBMS_OUTPUT.PUT_LINE('The total amount payable :
'|| :result);
END;
/
-- To see the value set for the variable on SQL prompt use the
SQL * plus command PRINT

PRINT result

CONFIDENTIAL© Copyright 2008 Tech


27
Mahindra Limited
PL/SQL Record Type Variable
• %TYPE and %ROWTYPE work with single value and one
complete record respectively
• How do we create our own composite data type, with
our own specified number of values to hold?
– Let us consider a table of about 20 columns
– We need to work with only seven of those columns
– If we use %ROWTYPE, we get all 20 values unnecessarily
– If we use seven %TYPE declarations it will be bit clumsy
– A better way to solve this problem is by defining our own
data type, which can hold seven values

CONFIDENTIAL© Copyright 2008 Tech


28
Mahindra Limited
PL/SQL Record Type Variable Example
DECLARE
TYPE myrec_type IS RECORD
(eno emp.empno%TYPE,
name emp.ename%TYPE,
esal emp.sal%TYPE);
emp_record myrec_type;
BEGIN
SELECT empno,ename,sal INTO emp_record.eno,
emp_record.name, emp_record.esal
FROM emp WHERE empno=7839;
DBMS_OUTPUT.PUT_LINE(‘Empno :’||emp_record.eno);
DBMS_OUTPUT.PUT_LINE(‘Ename :’||emp_record.name);
DBMS_OUTPUT.PUT_LINE(‘Salary :’||
emp_record.esal);
END;

CONFIDENTIAL© Copyright 2008 Tech


29
Mahindra Limited
Manipulating Data in PL/SQL
• To manipulate data in the database use DML statements
INSERT, UPDATE and DELETE in PL/SQL

• INSERT

DECLARE
v_empno emp.empno%TYPE := &empno;
v_ename emp.ename%TYPE := ‘&ename’;
v_salary emp.sal%TYPE := &sal;
BEGIN
INSERT INTO emp(empno,ename,sal)
VALUES(v_empno,v_ename,v_salary);
COMMIT;
END;

CONFIDENTIAL© Copyright 2008 Tech


30
Mahindra Limited
• Manipulating Data in PL/SQL
UPDATE

DECLARE
v_empno emp.empno%TYPE;
v_salary emp.sal%TYPE :=&sal;

BEGIN
UPDATE emp SET sal=v_salary where empno=1234;
COMMIT;
END;

CONFIDENTIAL© Copyright 2008 Tech


31
Mahindra Limited
Manipulating Data in PL/SQL
• DELETE

DECLARE
v_empno emp.empno%TYPE :=&eno;
BEGIN
DELETE emp WHERE empno=v_empno;
COMMIT;
END;

CONFIDENTIAL© Copyright 2008 Tech


32
Mahindra Limited
Sequence Object
• CREATE SEQUENCE MySeq
INCREMENT BY 1
START WITH 1
MAXVALUE 99999
NOCACHE
NOCYCLE;

• INSERT INTO emp (empno) VALUES(


MySeq.NEXTVAL);

CONFIDENTIAL© Copyright 2008 Tech


33
Mahindra Limited


Sequence Object: Example
CREATE SEQUENCE seq_emp;
SET SERVEROUTPUT ON

DECLARE
v_empno emp.empno%TYPE;
BEGIN
-- Using a sequence to autogenerate the primary key
column values
INSERT INTO emp (empno, ename)
VALUES(seq_emp.NEXTVAL,‘Ajay')
RETURNING empno INTO v_empno;
/* Displaying the value of the sequence that is
inserted in the table */
DBMS_OUTPUT.PUT_LINE(v_empno);
END;

CONFIDENTIAL© Copyright 2008 Tech


34
Mahindra Limited
PL/SQL Control Structures
• PL/SQL, like other 3GL has a variety of control
structures which include
– Conditional statements
– Loops
• Conditional Statements
There are three forms of IF statements
– IF-THEN-END IF;
– IF-THEN-ELSE-END IF;
– IF-THEN-ELSIF-END IF;
CONFIDENTIAL© Copyright 2008 Tech
35
Mahindra Limited
Example: IF..ELSE..END IF
-- Block to demonstrate IF...ELSE...END IF
DECLARE
vname emp.ename%TYPE;
veno emp.empno%TYPE := &Emp_Num;
vsal emp.sal%TYPE;

BEGIN
SELECT ename, sal INTO vname, vsal FROM emp WHERE empno = veno;
–- Displays an appropriate message if salary is greater
than 1500
IF vsal > 1500 THEN
DBMS_OUTPUT.PUT_LINE (vname|| ' earns a salary greater
than 1500');
--Else it shows the employee name whose sal is <1500
ELSE
DBMS_OUTPUT.PUT_LINE (vname|| ' earns a salary not greater
than 1500');
END IF;
DBMS_OUTPUT.PUT_LINE ('This line executes irrespective of the
condition');
END;

CONFIDENTIAL© Copyright 2008 Tech


36
Mahindra Limited
DECLARE
Example: Nested IF
firstNo NUMBER(5) := &firstNo;
secondNo NUMBER(5) := &secondNo;
BEGIN
IF firstNo IS NULL OR secondNo IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Improper Input');
ELSE
IF firstNo = secondNo THEN
DBMS_OUTPUT.PUT_LINE('The numbers are
equal');
ELSE
IF firstNO > secondNo THEN
DBMS_OUTPUT.PUT_LINE('The first no. is
greater');
ELSE
DBMS_OUTPUT.PUT_LINE('The second no. is
greater');
END IF;
END IF;
END IF;
END;
/ CONFIDENTIAL© Copyright 2008 Tech
37
Mahindra Limited
PL/SQL Control Structures
• LOOP Statements
– Simple Loops
– WHILE Loops
– FOR Loops

CONFIDENTIAL© Copyright 2008 Tech


38
Mahindra Limited
LOOP Statements
• Simple Loops
LOOP
Sequence_of_statements;
END LOOP;
Add EXIT statement to exit from the loop

• WHILE Loops
WHILE condition
LOOP
Statements;
END LOOP;
Condition is evaluated before each
iteration of the loop

CONFIDENTIAL© Copyright 2008 Tech


39
Mahindra Limited
LOOP Statement: Example

DECLARE
v_i NUMBER(2) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
EXIT WHEN v_i = 10;
v_i:=v_i+1;
END LOOP;
END;

CONFIDENTIAL© Copyright 2008 Tech


40
Mahindra Limited
WHILE Loop: Example

DECLARE
v_i NUMBER(2) := 1;
BEGIN
WHILE ( v_i <= 10 )
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
v_i:=v_i+1;
END LOOP;
END;

CONFIDENTIAL© Copyright 2008 Tech


41
Mahindra Limited
FOR Loops
• The number of iterations for simple loops and
WHILE loops is not known in advance, it depends
on the loop condition. Numeric FOR loops, on the
other hand, have defined number of iterations.
FOR counter IN [REVERSE] low_bound ..
high_bound
LOOP
Statements;
END LOOP;
– Where:
• counter: is an implicitly declared integer whose value automatically
increases or decreases by 1 on each iteration
• REVERSE: causes the counter to decrement from upper bound to
lower bound
• low_bound: specifies the lower bound for the range of counter values
• high_bound: specifies the upper bound for the range of counter
values

CONFIDENTIAL© Copyright 2008 Tech


42
Mahindra Limited
FOR Loop: Example

BEGIN
FOR v_i IN 1..10
/* The LOOP VARIABLE v_i of type BINARY_INTEGER
is declared automatically */
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
END LOOP;

END;

CONFIDENTIAL© Copyright 2008 Tech


43
Mahindra Limited
For Loop with EXIT condition
DECLARE
myNo NUMBER(5):= &myno;
counter NUMBER(5):=1;
BEGIN
FOR i IN 2..myNo-1
LOOP
counter:= counter+1;
EXIT WHEN myNo mod i = 0;
END LOOP;

IF counter = myNo-1 THEN


DBMS_OUTPUT.PUT_LINE( 'The given
number is prime' );
ELSE
DBMS_OUTPUT.PUT_LINE('The given number is not
a prime number' );
END IF;
END;
/

CONFIDENTIAL© Copyright 2008 Tech


44
Mahindra Limited
Summary
• In this session, we have covered,
– Oracle PL/SQL block structure
– Embedding SELECT and DML statements inside
PL/SQL block
– Oracle PL/SQL Control Structures

CONFIDENTIAL© Copyright 2008 Tech


45
Mahindra Limited
Thank You

You might also like