Академический Документы
Профессиональный Документы
Культура Документы
• 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
SQL integrated PL/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 orientation Object oriented Truly object oriented (like Java and
to a certain C++)
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
• 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
Oracle database and corresponding PL/SQL versions
PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
SQL statement
block block
executor
Oracle server
BLOCK
• Consists of
Declaration section(optional)
Execution section
Exception Section(optional)
TYPES OF BLOCK
• Anonymous block
• Named block
BLOCK SECTIONS
DECLARATION IDENTIFIERS
CURSORS
EXCEPTIONS
EXECUTABLE
STATEMENTS EXECUTION
EXCEPTION EXCEPTION
HANDLERS
VARIABLES
Temporarily Stores Data
Reusable
No white spaces
VNO INT;
1NO INT;
V NAM CHAR(1);
V/NAME VARCHAR2(10);
SAMPLE BLOCK
PROCEDURE
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);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;
/
Variable Initialization and Keywords
Examples:
v_hiredate := '01-JAN-2001';
v_ename := 'Maduro';
Scalar Data Types
25-OCT-99
“Four score and seven years
TRUE
ago our fathers brought
forth upon this continent, a
new nation, conceived in
256120.08 LIBERTY, and dedicated to
the proposition that all men
Atlanta
are created equal.”
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
• Example:
v_deptno 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: