PLSQL 1
PLSQL 1
• SQL IS A 4 GL TOOL
Meaning it uses constructs and elements that specify "what to do"
without having to specify "how to do it."
• PURPOSE OF SQL
DDL,DML,CONTROL,QUERYING
• PURPOSE OF 3 GL TOOLS
USES constructs, such as conditional or iterative execution etc.
(logic & control flow)
• PL/SQL
To accommodate 3GL features as a procedural extension to SQL
Bridges the gap b/w database and programming languages.
PL/SQL vs Other 3GLs
FEATURE PL/SQL OTHER 3GLS (JAVA, C++, C)
Ease of use Fairly easy Difficult; requires a steep learning
curve
Portability of Highly portable Portable except for system calls
applications
Integration with Tightly Integrated to a lesser degree than PL/
SQL integrated SQL; access by means of SQLJ or
JDBC
SQL-intensive Well suited Not well suited
operations
Compute- Not well suited Well suited (e.g., for sorting of large
intensive arrays)
operations
Object Object Truly object oriented (like Java and
orientation oriented to a C++)
certain extent
HISTORY OF PL/SQL
PL/SQL was first introduced in 1991 with Oracle 6.0. It was
provided as the "procedural option" on the server side. At the
same time, it was subsequently introduced on the client side
with SQL*Forms version 3.0 having a PL/SQL engine of its own.
The first version of PL/SQL, PL/SQL 1.0, had very limited
procedural features. But one of its strong points was its
capability to process multiple SQL statements mixed with
procedural constructs.
PL/SQL has its roots in ADA, a high-level programming
language. The concept of the PL/SQL block resembles the
concept of block structure in ADA using BEGIN and END blocks.
PL/SQL shares other features with ADA such as the syntax "="
used for comparison and ":=" used for assignment, exception
handling, and the declarative syntax of defining stored
subprograms.
Over the years, Oracle came up with new releases of PL/SQL. With
Oracle 7.0, Oracle released PL/SQL 2.0, which turned Oracle into an
active database with the capability to store business and application
logic in the database in the form of stored procedures, functions, and
packages. It also defined the capability to declare programmer-
defined records and arrays in the form of PL/SQL tables. PL/SQL 2.1
came into existence with Oracle 7.1 and enabled the use of stored
functions in SQL statements. Also, dynamic SQL was introduced in
PL/SQL for the first time with the DBMS_SQL package. Oracle 7.2 was
released subsequently, and along with it came PL/SQL 2.2. It had the
capability to define binary wrappers for PL/SQL stored subprograms,
thus hiding code from other developers. Also, the DBMS_JOB
package was introduced, which enabled programmers to submit jobs
from within the database. The next release of PL/SQL was PL/SQL
2.3, which was introduced with Oracle 7.3. It enhanced the
capabilities of PL/SQL tables with the ability to define new methods,
and it also enabled programmers to access the file system from
within the database. File I/O could be done using the UTL_FILE
package.
Oracle 8.x was a major breakthrough in the Oracle
database history with the introduction of objects and Java in
the database. PL/SQL 8.x was released along with Oracle 8.x
and included major features such as native dynamic SQL,
Java stored procedures, and system- and schema-level
database triggers.
• Portability
Programs written in PL/SQL are hardware independent and operating system
independent. (oracle server+IDE)
• Modularity
Write independent programming modules with procedures/functions/
packages
• Better Performance
Data type conversion isn't needed on input and output.
Network traffic is reduced
• OBJECT ORIENTATION
Encapsulation, inheritance, abstraction, polymorphism etc
Oracle database and corresponding PL/SQL versions
ORACLE PL-SQL CHARACTERISTICS
RELEASE VERSION
6.0 1.0 Initial version, used as scripting language in sql plus and a programming
language in sql forms 3.
7.0 2.0 Added support for stored procedures, functions, packages, programmer-
defined records, PL/SQL tables, and many package extensions.
7.1 2.1 Supported programmer-defined subtypes, enabled the use of stored
functions inside SQL statements, and offered dynamic SQL with the
DBMS_SQL package. With PL/SQL 2.1, you could execute SQL DDL
statements from within PL/SQL programs.
7.2 2.2 It had the capability to define binary wrappers for PL/SQL stored
subprograms, thus hiding code from other developers. Also, the
DBMS_JOB package was introduced, which enabled programmers to
submit jobs from within the database.
7.3 2.3 Enhanced functionality of PL/SQL tables, offered improved remote
dependency management, added file I/O capabilities to PL/SQL with the
UTL_FILE package, and completed the implementation of cursor
variables.
8.0 8.0 Reflected Oracle's effort to synchronize version numbers across related
products. PL/SQL 8.0 is the version of PL/SQL that supported
enhancements of Oracle8 Database, including large objects (LOBs),
object-oriented design and development, collections (VARRAYs and
nested tables), and Oracle/AQ (the Oracle/Advanced Queuing facility).
Oracle database and corresponding PL/SQL versions
ORACLE PL-SQL CHARACTERISTICS
RELEASE VERSION
8.1 8.1 The first of Oracle's i series, the corresponding release of PL/SQL offered a
truly impressive set of added functionality, including a new version of
dynamic SQL, support for Java in the database, the invoker rights model, the
execution authority option, autonomous transactions, and high-performance "
bulk" DML and queries.
9.1 9.1 The first release of this version included support for inheritance in object
types, table functions and cursor expressions (allowing for parallelization of
PL/SQL function execution), multilevel collections and the CASE statement
and CASE expression.
9.2 9.2 Oracle9i Database Release 2 put a major emphasis on XML (Extensible
Markup Language) but also had some treats for PL/SQL developers, including
associative arrays that can be indexed by VARCHAR2 strings in addition to
integers, record-based DML (allowing you to perform an insert using a record,
for example), and many improvements to UTL_FILE (which allows you to
read/write files from within a PL/SQL program).
10.1 10.1 Oracle Database 10g Release 1 was unveiled in 2004 and focused on support
for grid computing, with an emphasis on improved/automated database
management. From the standpoint of PL/SQL, the most important new features
are transparently available to developers: an optimized compiler and compile-
time warnings.
10.2 10.2 Oracle Database 10g Release 2, coming out in 2005, offers a small number of
new features for PL/SQL developers, most notably support for preprocessor
syntax that allows you to conditionally compile portions of your program,
depending on Boolean expressions you define.
PL/SQL Environment
PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
statement
block block SQL
executor
Oracle server
BLOCK
• Consists of
Declaration section(optional)
Execution section
Exception Section(optional)
TYPES OF BLOCK
• Anonymous block
• Named block
BLOCK SECTIONS
DECLARATION
EXECUTABLE
STATEMENTS EXECUTION
EXCEPTION EXCEPTION
HANDLERS
LEXICAL UNITS
Variables(Identifiers)
Delimeters
Values
Comments
VARIABLES
Temporarily Stores Data
Reusable
No white spaces
V NAM CHAR(1);
V/NAME VARCHAR2(10);
SAMPLE BLOCK
BEGIN
END;
TERMINATOR
OUTPUT
PL/SQL procedure successfully completed.
SET SERVEROUT ON
BLOCK WITH VARIABLES
DECLARE
BEGIN
DBMS_OUTPUT . PUT_LINE(V_MSG);
END;
BLOCK FOR SELCTING TABLE COLUMN
DECLARE
V_NAME VARCHAR2(10);
BEGIN
SELECT ENAME
INTO V_NAME
FROM EMP
WHERE EMPNO=7369;
DBMS_OUTPUT . PUT_LINE(V_NAME);
END;
GOLDEN RULES OF EXECUTION SECTION
SELECT SHOULD HAVE AN INTO CLAUSE
DECLARE
V_NAME VARCHAR2(10);
BEGIN
SELECT ENAME
INTO V_NAME
FROM EMP
WHERE EMPNO=7369;
DBMS_OUTPUT . PUT_LINE(V_NAME);
END;
DML OPERATIONS USING PL/SQL
SQL> create table e2 as select empno,ename from emp;
Table created.
SQL> declare
v_no emp.empno%type;
v_name emp.ename%type;
begin
insert into e2 values(1,'xyz');
end;
/
PL/SQL procedure successfully completed.
SQL> select * from e2;
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
1 xyz
15 rows selected.
DML OPERATIONS USING PL/SQL
SQL> declare
v_eno e2.empno%type :=1;v_ename e2.ename%type :='RAMU';
begin
update e2 set ename=V_ENAME WHERE EMPNO=V_ENO;
END;
/
SQL> SELECT * FROM E2;
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
1 RAMU
DML OPERATIONS USING PL/SQL
SQL> declare
v_eno e2.empno%type :=1;
begin
Delete from emp WHERE EMPNO=V_ENO;
END;
/
SQL> SELECT * FROM E2;
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
Procedural constructs
• Conditional constructs
if elsif else
CASE
• Iterative constructs
• simple loop
• numeric for loop
• while loop
• nested loops
If elsif else
DECLARE
a number := 50;
b number := -20;
BEGIN
IF (a>b) THEN
dbms_output.put_line('A is greater than B');
ELSIF (a<b) THEN
dbms_output.put_line('A is less than B');
ELSE
dbms_output.put_line('A is equal to B');
END IF;
END;
SIMPLE LOOP
DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
i NUMBER := 1;
BEGIN
LOOP
actual_line := actual_line || separator;
EXIT WHEN i = line_length;
i:= i + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
/
WHILE LOOP
DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
idx NUMBER := 1;
BEGIN
WHILE (idx<=line_length) LOOP
actual_line := actual_line || separator;
idx := idx +1 ;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
FOR LOOP
DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
BEGIN
FOR idx in 1..line_length LOOP
actual_line := actual_line || separator;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
Block Structure for Anonymous PL/SQL
Blocks
DECLARE (optional)
Declare PL/SQL objects to be used
within this block
BEGIN (mandatory)
Define the executable statements
EXCEPTION (optional)
Define the actions that take place if
an error arises
END; (mandatory)
Block Structure for PL/SQL
Subprograms
Header
IS|AS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception section
END;
PL/SQL ENVIRONMENT
• Development
• Execution
• Debugging
• PL/SQL variables:
– Scalar
– Composite
– Reference
– LOB (large objects)
• Non-PL/SQL variables: Bind and host
variables
Guidelines for Declaring PL/SQL
Variables
• Follow naming conventions.
• Initialize variables designated as NOT
NULL and CONSTANT.
• Declare one identifier per line.
• Initialize identifiers by using the
assignment operator (:=) or the
DEFAULT reserved word.
identifier :=expr ;
Naming Rules
• Two variables can have the same name,
provided they are in different blocks.
• The variable name (identifier) should not be
the same as the name of table columns used
in the block.
DECLARE
employee_id NUMBER(6); Adopt a naming
BEGIN
SELECT employee_id convention for
INTO employee_id PL/SQL identifiers:
FROM employees
WHERE last_name = 'Kochhar';
for example,
END; v_employee_id
/
Variable Initialization and Keywords
Examples:
v_hiredate := '01-JAN-2001';
v_ename := 'Maduro';
Scalar Data Types
25-OCT-99
“Four score and seven years
ago our fathers brought TRUE
forth upon this continent, a
new nation, conceived in
256120.08 LIBERTY, and dedicated to
the proposition that all men
are created equal.” Atlanta
Base Scalar Data Types
• CHAR [(maximum_length )]
• VARCHAR2 (maximum_length )
• LONG
• LONG RAW
• NUMBER [(precision, scale )]
• BINARY_INTEGER
• PLS_INTEGER
• BOOLEAN
Base Scalar Data Types
• DATE
• TIMESTAMP
• TIMESTAMP WITH TIME ZONE
• TIMESTAMP WITH LOCAL TIME
ZONE
• INTERVAL YEAR TO MONTH
• INTERVAL DAY TO SECOND
Scalar Variable Declarations
Examples:
DECLARE
v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
v_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
...
The %TYPE Attribute
Examples:
...
v_name employees.last_name%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 10;
...
Declaring Boolean Variables
• Only the values TRUE, FALSE, and
NULL can be assigned to a Boolean
variable.
• The variables are compared by the
logical operators AND, OR, and NOT.
• The variables always yield TRUE,
FALSE, or NULL.
• Arithmetic, character, and date
expressions can be used to return a
Boolean value.
Using Bind Variables
SET SERVEROUTPUT ON
DEFINE p_annual_sal = 60000
DECLARE
v_sal NUMBER(9,2) := &p_annual_sal;
BEGIN
v_sal := v_sal/12;
DBMS_OUTPUT.PUT_LINE ('The monthly salary is ' ||
TO_CHAR(v_sal));
END;
/
SELECT Statements in PL/SQL
• The INTO clause is required.
• Queries must return one and only one
row.
DECLARE
• v_deptno
Example:NUMBER(4);
v_location_id NUMBER(4);
BEGIN
SELECT department_id, location_id
INTO v_deptno, v_location_id
FROM departments
WHERE department_name = 'Sales';
...
END;
/
RETRIEVING DATA IN PL/SQL
DECLARE
v_hire_date emp.hiredate%TYPE;
v_sal emp.sal%TYPE;
BEGIN
SELECT hire_date, sal
INTO v_hire_date, v_sal
FROM emp
WHERE employee_id = 100;
...
END;
/
RETRIEVING DATA IN PL/SQL
SET SERVEROUTPUT ON
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(sal) -- group function
INTO v_sum_sal
FROM emp
WHERE dept_id = v_deptno;
DBMS_OUTPUT.PUT_LINE ('The sum sal is ' ||
TO_CHAR(v_sum_sal));
END;
/
1. What are the four keywords of the basic PL/SQL block? What happens in each area?
[DECLARE
Declare local variables
]BEGIN
Executable statements
[EXCEPTION
Error handling statements
]END;
• company_id#
• primary_acct_responsibility
• First_Name
• FirstName
• address_line1
• S123456
The following identifiers are all illegal in PL/SQL: