Beruflich Dokumente
Kultur Dokumente
Introduction To PL/SQL
1. Introduction To PL/SQL
1.
2.
mukeshtekwani@hotmail.com
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
Oracle Engine
PL/SQL Engine
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
mukeshtekwani@hotmail.com
-- 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
mukeshtekwani@hotmail.com
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
mukeshtekwani@hotmail.com
/* 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
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>
mukeshtekwani@hotmail.com
/
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.
/
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
AREA
---------28.26
50. 24
78.5
113.04
153.86
10
/* 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
11
12
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
mukeshtekwani@hotmail.com