Sie sind auf Seite 1von 12

Chap 1.

Introduction To PL/SQL

1. Introduction To PL/SQL
1.

What is PL/SQL? What are the disadvantages of SQL?


PL/SQL stands for Procedural Language extension to SQL. PL/SQL is a 3GL which extends
SQL by adding programming capabilities, such as programming structures and subroutines,
similar to those available in high-level languages. Thus, PL/SQL is a super set of SQL.
PL/SQL is a block-structured language i.e., each bock can perform one logical unit of a job.
PL/SQL is used for server-side and client-side development. PL/SQL is also used to develop
applications for browsers.
SQL is a natural language for database management system but some of the drawbacks of
SQL are as follows:
1. SQL does not have the capabilities of programming languages such as looping, branching,
checking for conditions, etc. These capabilities are important before data storage.
2. SQL does not have error-handling capabilities. While processing or executing a SQL
statement if an error occurs, Oracle displays its own error messages.
3. SQL statements are passed to the Oracle engine, one at a time. Every time a statement is
executed, a call is made to the engines resources. This decreases the data processing speed
as repeated calls must be made to the network.

2.

What are the advantages of PL/SQL?


PL/SQL is used in most Oracle products. The advantages of PL/SQL are as follows:
1. Development tool: PL/SQL is a development tool. It supports SQL data management.
2. OOPs: PL/SQL has support for object-oriented programs and this provides the advantages
of data encapsulation or data hiding.
3. Better Performance: When a PL/SQL block is processed then the entire block is sent to the
server and not just individual statements. So if a PL/SQL block contains many SQL
statements, then it is treated as one call to the server. If PL/SQL is not used then each SQL
statement will result in a separate call to the database server.
4. Improved error handling: PL/SQL permits user-friendly error messages to be displayed
instead of the standard cryptic Oracle error messages.
5. Variables can be declared and used in blocks of code. These variables can be used to store
intermediate values of calculations or query processing and used later. Calculation can be
done and stored in Oracle tables.
6. Portability: Applications developed in PL/SQL are portable across any platform
hardware and software, including operating systems.
7. Higher Productivity: Users can do procedural programming.
8. Integration with Oracle: PL/SQL supports all SQL datatypes.
9. Support for developing web applications and pages.
10. Access to pre-defined packages.

Explain the generic PL/SQL block.


Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.
A PL/SQL Block consists of three sections:
The Declare section (optional): The Declaration section of a PL/SQL Block starts with the

mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

Chap 1. Introduction To PL/SQL

reserved keyword DECLARE. This section is optional and is used to declare any variables,
constants, records and cursors, which are used to manipulate data in the execution section.
The Begin or Execution section: This section begins with the keyword BEGIN and ends
with the keyword END. It consists of a set of SQL and PL/SQL statements which describe
processes that have to be applied to the table data. This section contains statements for data
manipulation, looping, branching and data retrieval.
The Exception (or Error) Handling section (optional) The Exception section of a
PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional.
Any errors in the program can be handled in this section, so that the PL/SQL Blocks
terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the
Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.
A typical code block looks like this:
DECLARE
Declaration of Variables, constants, cursors, etc
BEGIN
SQL executable statements and PL/SQL executable statements
EXCEPTION
SQL block to handle errors that may arise due to execution of
code in the BEGIN block.
END;
/

Note the / sign at the end of the code. This tells Oracle to run the block. If the procedure is
completed successfully, Oracle generates the following message: PL/SQL procedure
completed successfully.
4

Explain the PL/SQL Execution environment / PL/SQL architecture


The PL/SQL engine is a part of the Oracle engine. The Oracle engine can process
individual SQL statements and also PL/SQL blocks.
Blocks of code are sent to the PL/SQL engine where the procedural statements are
executed and the SQL statements are sent to the SQL executor in Oracle engine.
When a number of SQL statements are combined into a PL/SQL block, the call to the
Oracle engine is made only once. This process is illustrated below:
PL/SQL block of code
DECLARE
Procedural statements;
BEGIN
Procedural Statements;
SQL statements;
EXCEPTIONS
SQL statements;
END

Oracle Engine
PL/SQL Engine

SQL statement Executor

The PL/SQL compilation and run-time system is an engine that compiles and executes
PL/SQL blocks and subprograms. The engine can be installed in an Oracle server or in an
Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Chap 1. Introduction To PL/SQL

application development tool such as Oracle Forms.


The PL/SQL engine executes procedural statements but sends SQL statements to the SQL
engine in the Oracle database. This is shown in the following figure:

Write a note on PL/SQL Character Set.


Character set of PL/SQL is as follows:
upper- and lower-case letters A .. Z and a .. z
numerals 0 .. 9
symbols ( ) + - * / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ] tabs, spaces, and carriage returns
Lexical units: Words used in PL/SQL are called lexical units. Blank spaces have no effect on
the PL/SQL block.
E.g.,
IF x > y THEN
max := x;
ELSE
max := y;
END IF;
Compound symbols used in PL/SQL are >= <= != || >> << := **
Literals: It is a numeric value or a character string.
Numeric Literal: These can be either integer or float. E.g., 35, 3.142
Character literal: It consists of a single character enclosed between single quotes sign. E.g.
A.
String Literal: These are characters stored in single quotes. E.g., Mumbai. If a single quote
character must itself be a part of the string literal, than it must appear twice, e.g., Mumbais
weather is good.
Logical (Boolean) literal: These are predetermined constants with values of TRUE, FALSE
or NULL.
Comments
The PL/SQL compiler ignores comments, but we should put comments to improve code
readability and maintenance. PL/SQL supports two comment styles: single-line and multi-line.
Single-Line Comments: Single-line comments begin with a double hyphen (--) anywhere on
a line and extend to the end of the line. A few examples are:

mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

Chap 1. Introduction To PL/SQL

-- begin processing
SELECT sal INTO salary FROM emp -- get current salary
WHERE empno = emp_id;
bonus := salary * 0.15; -- compute bonus amount
Comments can appear within a statement at the end of a line.
While testing or debugging a program, you might want to disable a line of code. The following
example shows how you can "comment-out" the line:
-- DELETE FROM emp WHERE comm IS NULL;
Multi-line Comments
Multi-line comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can
span multiple lines. This is similar to C or Java style. Examples are:
BEGIN
...
/* Compute a 15% bonus for top-rated employees. */
IF rating > 90 THEN
bonus := salary * 0.15
/* bonus is based on salary */
ELSE
bonus := 0;
END IF;
...
/* The following line computes the area of a circle using pi, which is the ratio between
the circumference and diameter. */
area := pi * radius**2;
END;
6

Write a note on PL/SQL data types.


Every constant, variable, and parameter has a datatype (or type), which specifies a storage
format, constraints, and valid range of values. PL/SQL provides a variety of predefined
datatypes. E.g., integer, floating point, character, Boolean, date, collection, reference, and
LOB types. In addition, PL/SQL lets you define your own subtypes.
The default types in PL/SQL are: number, char, boolean, and date.
Declaring variables:
DECLARE
part_no NUMBER(6);
part_name VARCHAR2(20);
in_stock BOOLEAN;
part_price NUMBER(6,2);
part_desc VARCHAR2(50);
hours_worked NUMBER := 40; --declare and assign value
The %TYPE attribute:
PL/SQL uses the %TYPE attribute to declare a variable based on definitions of columns in a
table. Therefore, if a columns attributes change, the variables attributes (data type) will also
change. The obvious benefits are: data independence, reduces maintenance costs and allows
programs to change according to changes in the table.

Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Chap 1. Introduction To PL/SQL

Example:
credit REAL(7,2);
debit credit%TYPE;
NOT NULL causes creation of a variable or a constant that cannot be assigned a null value. If
a null value is assigned to such a variable or constant, Oracle will generate an exception
condition (error). Every variable or constant declared as NOT NULL must be followed by a
PL/SQL statement that assigns a value to the variable or constant.
Example:
acct_id INTEGER(4) NOT NULL := 9999;
Assigning values to variables:
Values are assigned to variables by using the assignment operator := (i.e. the colon sign,
followed by the equal sign).
Selecting or fetching table data values into variables.
Declaring Constants:
A constant is declared by adding the keyword constant to the variable name and assigning it a
value immediately. Values of constants cannot be changed in PL/SQL block.
RAW types: These are used to store binary data.
LOB Types: The LOB (large object) datatypes BFILE, BLOB, CLOB, and NCLOB let you
store blocks of unstructured data (such as text, graphic images, video clips, and sound
waveforms) up to four gigabytes in size.
7

Write a note on the conditional control structure in PL/SQL .


The conditional structures in PL/SQL are:
1. IF .ENDIF statement
2. IF..THEN..ELSE..END IF statement.
3. IF..THEN..ELSIF..ELSEEND IF statement (Note: observe carefully the spelling of
ELSIF)
Example: Write a PL/SQL block that will accept an account number from tehuser, check is
the users balance is less than the minimum balance, and only then deduct Rs 200 as penalty
from the balance. The process is fired on the ACCT_MST table.
DECLARE
/* we first declare the memory variables and constants */
mCURBAL NUMBER (11,2);
mACCTNO VARCHAR2(7); /* VARCHAR2datatype stores variable length character data */
mPENALTY NUMBER(4) := 200;
mMINBAL NUMBER (7, 2) := 10000.00;
BEGIN
/* accept the account number from the user */
mACCTNO := &ACCTNO;
/* retrieve the current balance from the ACCT_MST table */
SELECT URBAL INTO mCURBAL FROM ACCT_MST WHERE ACCTNO = mACCTNO

mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

Chap 1. Introduction To PL/SQL

/* Now check if the balance is less than minimum balance and if so, deduct 200 as penalty */
IF mCURBAL < mMINBAL THEN
UPDATE ACCT_MST SET CURBAL = CURBAL mPENALTY
WHERE ACCTNO = mACCTNO;
END IF;
END;
/
Example2: Using a Simple IF-THEN-ELSE Statement
DECLARE
sales NUMBER(8,2) := 12100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
ELSE
bonus := 50;
END IF;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END;
/
Example3: Using the IF-THEN-ELSEIF Statement
DECLARE
sales NUMBER(8,2) := 20000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus := 500;
ELSE
bonus := 100;
END IF;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END;
/
Example4: Using the CASE statement
SQL> DECLARE
2 grade CHAR(1);
3 BEGIN
4 grade := 'B';
5
6 CASE grade
7
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
8
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');
Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Chap 1. Introduction To PL/SQL

9
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');
10
WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');
11
WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');
12
ELSE DBMS_OUTPUT.PUT_LINE('No such grade');
13 END CASE;
14 END;
15 /
Output:
Very Good
PL/SQL procedure successfully completed.
SQL>

Write a note on Iterative Control statements in PL/SQL .


Iterative statements execute a set of statements (or a loop) repeatedly. The keyword LOOP is
used before the first statement in the sequence of statements that has to be repeated. The
keyword END LOOP is used to indicate the end of a loop. There must be a conditional
statement that can control the number of times the loop is executed else the loop will go on
forever (infinite loop).
Syntax:
LOOP
sequence_of_statements
END LOOP;
With each iteration of the loop, the sequence of statements is executed, then control resumes at
the top of the loop. You use an EXIT statement to stop looping and prevent an infinite loop.
You can place one or more EXIT statements anywhere inside a loop, but not outside a loop.
There are two forms of EXIT statements: EXIT and EXIT-WHEN.
The following are important steps to be followed while using this simple looping structure.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use an EXIT WHEN statement to exit from the Loop based on a condition. If you use an
EXIT statement without WHEN condition, the statements in the loop is executed only
once.
Example 1: Create a simple loop so that a message is displayed when a loop exceeds a
particular value.
DECLARE
n NUMBER := 0;
BEGIN
LOOP
n := n + 2;
EXIT WHEN n > 10;
END LOOP:
dbms_output.put_line (Loop exited as n has reached the value || TO_CHAR(n));
END;

mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

Chap 1. Introduction To PL/SQL

/
In this code, the statement dbms_output.put_line() is used to display ay message you want, on the
screen. Here, put_line is the procedure that generates the output on the screen and dbms_output is the
package to which put_line() belongs.

Example 2: This illustrates the use of the EXIT statement in looping.


DECLARE
credit_rating NUMBER := 0;
BEGIN
LOOP
credit_rating := credit_rating + 1;
IF credit_rating > 3 THEN
EXIT; -- exit loop immediately
END IF;
END LOOP;
-- control resumes here
DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating));
IF credit_rating > 3 THEN
RETURN;
-- use RETURN not EXIT when outside a LOOP
END IF;
DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating));
END;

/
The RETURN statement immediately ends the execution of a subprogram and returns control
to the caller.
The WHILE loop:
Syntax:
WHILE <condition>
LOOP
<action>
END LOOP;
Example 3: Write a PL/SQL code block to calculate the area of a circle for radius varying
between 3 and 7. Store the corresponding radius and area values in an empty table named
AREAS, consisting of columns RADIUS and AREA.
Step 1: We first create the table AREAS as follows:
CREATE TABLE AREAS (radius NUMBER(5), area NUMBER(14, 2));
Step 2: PL/SQL code:
DECLARE
pi CONSTANT NUMBER(4,2) :=3.14;
radius NUMBER(5);
area NUMBER (14, 2);
BEGIN
radius := 3;
WHILE radius <= 7
LOOP
Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Chap 1. Introduction To PL/SQL

area := pi * power(radius, 2);


INSERT INTO AREAS VALUES (radius, area);
radius := radius + 1;
END LOOP;
END;
/
Output:
SQL> select * from areas
2 ;
RADIUS
---------3
4
5
6
7

AREA
---------28.26
50. 24
78.5
113.04
153.86

The FOR loop:


As in other programming languages the FOR LOOP is used to execute a set of statements for a
predetermined number of times. Iteration occurs between the start and end integer values
given. The counter is always incremented by 1. The loop exits when the counter reaches the
value of the end integer.
Syntax:
FOR var IN startval...endval
LOOP statements;
END LOOP;
The variable in the FOR statement need not be declared. The increment value cannot be
specified and the variable always increments by 1.
Example : Using the FOR-LOOP
DECLARE
n NUMBER := 10;
BEGIN
FOR i IN 1..n LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/
Example: Write a PL/SQL code to reverse a number. E.g., the number 3718 becomes
8173.
DECLARE
orgnum VARCHAR(5) := 3718;
numlen NUMBER(2);
revnum VARCHAR(5);
BEGIN
numlen := length(orgnum);
mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

10

Chap 1. Introduction To PL/SQL

/* Now we initialize the loop so that it repeats the number of times equal to the length
of the original number. Since the number must be inverted, the loop should start from
the last digit and store it */
FOR ctr IN REVERSE 1..numlen
LOOP
revnum := revnum || SUBSTR(orgnum, ctr, 1);
END LOOP;
DBMS_OUTPUT.PUT_LINE(The original number is || orgnum);
DBMS_OUTPUT.PUT_LINE(The reversed number is || revnum);
END;
/

Write a note on Sequential Control statement (GOTO) in PL/SQL and the use of the
NULL statement.
The sequential control statement in PL/SQL is the GOTO statement. By default, statements are
executed sequentially (one after the other) but sometimes it may be necessary to change this
normal sequential flow. This statement changes the flow of control in a PL/SQL block.
The block of code to which control must be transferred in this way is marked with a tag. The
GOTO statement makes use of this user-defined name or tag to jump into that block of code.
The important point to note is that the label must appear before an executable statement.
Syntax:
GOTO <codeblock name>;
Example:
GOTO dogracing;
Write a PL/SQL code to achieve the following: If no transactions have taken place in the last
365 days, then mark the bank account as inactive and then record the account number, the
opening date, and the type of account in the INACTIVEMASTER table.
Step1:
CREATE TABLE INACTIVEMASTER
(
ACCTNO VARCHAR2(10),
OPENDT DATE,
TYPE VARCHAR2(2)
);

Step 2:
Now we create the PL/SQL code:
DECLARE
mACCTNO VARCHAR2(10);
mANS VARCHAR2(3);
mOPENDT DATE;
mTYPE VARCHAR2(2);
BEGIN
Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Chap 1. Introduction To PL/SQL

/* Accept the account number from the user */


mACCTNO := &mACCTNO;
SELECT YES INTO mANS FROM TRANSMSTR WHERE ACCTNO =
mACCTNO GROUP BY ACCTNO HAVING MAX(SYSDATE DT) > 365;
/* If no transactions have taken place in the last 365 days, control is transferred to a
user-labelled section of the code */
IF mANS = yes THEN
GOTO mark_status;
ELSE
DBMS_OUTPUT.PUT_LINE(Account number || mACCTNO || is active);
END IF;
<<mark_status>>
UPDATE ACCTMSTR STATUS = I WHERE ACCTNO = mACCTNO;
SELECT OPNDT, TYPE INTO mOPNDT, mTYPE FROM ACCTMSTR
WHERE ACCTNO = mACCTNO;
INSERT INTO INACTIVEMASTER (ACCTNO, OPNDT, TYPE)
VALUES (mACCTNO, mOPNDT, mTYPE);
dbms_output.put_line(Account Number: || mACCTNO || is marked as inactive);
END;
There are some restrictions on where the GOTO statement is allowed. A GOTO statement
cannot branch into an IF statement, CASE statement, LOOP statement, or sub-block. For
example, the following GOTO statement is not allowed:
BEGIN
...
GOTO update_row;
...
IF valid THEN
...
<<update_row>>
UPDATE emp SET ...
END IF;
END;

-- can't branch into IF statement

The NULL statement:


The NULL statement does nothing other than pass control to the next statement. The following
code demonstrates the use of the NULL statement:
DECLARE
done BOOLEAN;
BEGIN
...
FOR i IN 1..50 LOOP
IF done THEN
GOTO end_loop;
mukeshtekwani@hotmail.com

Prof. Mukesh N. Tekwani

11

12

Chap 1. Introduction To PL/SQL

END IF;
...
<<end_loop>> -- not allowed
END LOOP; -- not an executable statement
END;
The label end_loop in the above example is not allowed because it does not precede an
executable statement. We solve this problem by using the NULL statement as follows:
FOR i IN 1..50 LOOP
IF done THEN
GOTO end_loop;
END IF;
...
<<end_loop>>
NULL;
-- an executable statement
END LOOP;
9

Write PL/SQL code to check whether a number is a prime number.


SQL> DECLARE
2 p VARCHAR2(30);
3 n INTEGER := 37;
4 BEGIN
5 FOR j in 2..ROUND(SQRT(n)) LOOP
6
IF n MOD j = 0 THEN
7
p := ' is not a prime number';
8
GOTO print_now;
9
END IF;
10 END LOOP;
11
12 p := ' is a prime number';
13
14 <<print_now>>
15 DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
16 END;
17 /
37 is a prime number
PL/SQL procedure successfully completed.
SQL>

Prof. Mukesh N Tekwani

mukeshtekwani@hotmail.com

Das könnte Ihnen auch gefallen