Advanced Database PL SQL
Advanced Database PL SQL
Advanced Database PL SQL
Advanced Database
Lab Session
Compiled by Miliyon A
Compiled by Miliyon A 1
Basics of SQL *Plus
Compiled by Miliyon A 2
Basics of SQL * Plus
The SQL database language allows you to
store and retrieve data in Oracle.
PL/SQL allows you to link several SQL
commands through procedural logic.
SQL*Plus enables you to execute SQL
commands and PL/SQL blocks, and to
perform many additional tasks as well.
Compiled by Miliyon A 3
Basics of SQL * Plus
Through SQL*Plus, you can
® enter, edit, store, retrieve, and run SQL commands and
PL/SQL blocks format,
® perform calculations on, store, print and create web
output of query results
® list column definitions for any table access and
® copy data between SQL databases
® send messages to and accept responses from an end user
® perform database administration
Compiled by Miliyon A 4
PL/SQL
PL/SQL is a procedural language designed
specifically to embrace SQL statements within its
syntax.
® PL/SQL program units are compiled by the
Oracle Database server and stored in the
database.
® SQL is used to write queries DDL and DMLs.
® SQL/PL: is used to write program blocks,
functions procedures triggers and packages.
Compiled by Miliyon A 5
SQL, PL/SQL and SQL Plus
As described earlier
® SQL is used to write queries DDL and DMLs.
® SQL/PL: is used to write program blocks,
functions procedures triggers and packages.
Whereas SQP *Plus is
An Oracle product is used to run SQL and
PL/SQL statements.
Compiled by Miliyon A 6
Basic Concepts
The following definitions explain concepts central to SQL*Plus:
®Command: An instruction you give SQL*Plus or Oracle.
®Block: A group of SQL and PL/SQL commands related
to one another through procedural logic.
®table : The basic unit of storage in Oracle.
®query : A SQL command (specifically, a SQL SELECT
command) that retrieves information from one or more
tables.
®query results: The data retrieved by a query.
Compiled by Miliyon A 7
Who Can Use SQL*Plus
® The SQL*Plus, SQL, and PL/SQL command languages are powerful
enough to serve the needs of users with some database experience,
yet straightforward enough for new users who are just learning to
work with Oracle.
® The design of the SQL*Plus command language makes it easy to
use. For example, to give a column labeled ENAME in the database
the clearer heading "Employee", you might enter the following
command:
COLUMN ENAME HEADING EMPLOYEE
Similarly, to list the column definitions for a table called EMP, you
might enter this command:
DESCRIBE EMP
Compiled by Miliyon A 8
Conventions for Command Syntax
Compiled by Miliyon A 9
What You Need to Run SQL*Plus
Compiled by Miliyon A 10
What is SQL * Plus?
Compiled by Miliyon A 11
Connecting to database
Compiled by Miliyon A 12
Connecting to database
An alternative way of connecting to database can be done using
commandline
Open CMD as Administrator
Type SQLplus
On the prompt type the user name and password press enter
after successful login you will seethe screen
Compiled by Miliyon A 13
Writing Sample program using SQL * plus
Compiled by Miliyon A 14
PL SQL Overview
Compiled by Miliyon A 17
Writing Sample program using SQL * plus
Compiled by Miliyon A 19
Blocks in PL SQL
Compiled by Miliyon A 20
The 'Hello World' Example
1. DECLARE // is a keyword
2. message varchar2(20):= 'Hello, World!'; // declaration
3. BEGIN //beginning the executable command
4. dbms_output.put_line(message); // the statement
5. END; // end of the program
Alternatively the above code can be written without
declaration as follows
6. BEGIN
7. dbms_output.put_line(‘Hello World’);
8. END;
Compiled by Miliyon A 21
Advantages of PL SQL
Compiled by Miliyon A 22
PL/SQL in Client/Server Architecture
Compiled by Miliyon A 23
PL/SQL engine
The PL/SQL engine processes and executes any PL/SQL statements and
sends any SQL statements to the SQL statement processor.
When the PL/SQL engine is located on the server, the whole PL/SQL
block is passed to
the PL/SQL engine on the Oracle server. The PL/SQL engine processes
the block according to Figure
Compiled by Miliyon A 24
PL/SQL engine
Compiled by Miliyon A 25
PL/SQL engine in the client side
Compiled by Miliyon A 26
PL/SQL in SQL*Plus
SQL*Plus is an interactive tool that allows you to type SQL or PL/SQL
statements at the command prompt.
The command sent from SQL *Plus is sent to the SQL processor and
PL/SQL engine.
After they are processed, the results are sent back from the database
and are displayed on the screen.
However, there are some differences between entering SQL and PL/SQL
statements.
Compiled by Miliyon A 27
PL/SQL in SQL*Plus ….
Consider the following example of a SQL statement:
SELECT first_name, last_name FROM student;
As soon as you type the semicolon & press Enter, result is displayed.
1. BEGIN
2. DBMS_OUTPUT.PUT_LINE(“Hello There!”);
3. End;
4. .
5. /
Two additional lines at the end of the block contain . and /.
When SQL*Plus reads a PL/SQL block, a semicolon marks the end of the
individual statement within the block.
As you can see here, this can be done with a period and a slash.
Compiled by Miliyon A 29
Another PL SQL block code sample
Look at the following code
1. DECLARE
2. v_student_id NUMBER := &sv_student_id;
3. v_first_name VARCHAR2(35);
4. v_last_name VARCHAR2(35);
5. BEGIN
6. SELECT first_name, last_name INTO v_first_name, v_last_name FROM student
WHERE student_id = v_student_id;
PL/SQL is Programming tool within the Oracle not a stand-alone programming language.
As a result, it does not really have capabilities to accept input from a user.
However, SQL*Plus allows a PL/SQL block to receive input information with the help of
substitution variables.
Substitution variables cannot be used to output values, because no memory is allocated for them.
SQL*Plus substitutes a variable before the PL/SQL block is sent to the database.
Substitution variables usually are prefixed by the ampersand (&) or double ampersand (&&)
characters.
When this example is executed, the user is asked to provide a value for the student ID.
The student’s name is then retrieved from the STUDENT table if there is a record with the given
student ID.
If there is no record with the given student ID, the message from the exception-handling section is
displayed on the screen.
Compiled by Miliyon A 31
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE is a call to the procedure PUT_LINE.
The size of the buffer can be set between 2,000 and 1,000,000 bytes.
The second SET statement not only enables the DBMS_OUTPUT. PUT_LINE
statement, but also changes the buffer size from its default value to 5,000 bytes.
Compiled by Miliyon A 32
To stop writing to the screen type the code: SET SERVEROUTPUT OFF;
PL/SQL Programming Fundamentals
Compiled by Miliyon A 34
Using PL/SQL language components
PL/SQL lexical units fall within one of the following five groups:
2) Reserved words are words that PL/SQL saves for its own use (such as
BEGIN, END, and SELECT).
5)Compiled
Comments can be either single-line comments (--) or multiline
by Miliyon A 35
In other words, the PL/SQL compiler treats the portion of the variable
name after the ampersand (last_names) as a substitution variable.
As a result, you are prompted to enter the value for the last_names
Compiled by Miliyon A 37
variable every time the compiler encounters it.
illegal variable demonstration
Consider the code below and its output
SET SERVEROUTPUT ON
DECLARE
v_name VARCHAR2(30);
v_dob DATE;
v_us_citizen BOOLEAN;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_name||'born on'||v_dob);
END;
Output
born on
2. DECLARE
3. v_var1 VARCHAR2(20);
4. v_var2 VARCHAR2(6);
5. v_var3 NUMBER(5,3);
6. BEGIN
7. v_var1 := 'string literal';
8. v_var2 := '12.345';
9. v_var3 := 12.345;
10.DBMS_OUTPUT.PUT_LINE('v_var1: '||v_var1);
11.DBMS_OUTPUT.PUT_LINE('v_var2: '||v_var2);
12.DBMS_OUTPUT.PUT_LINE('v_var3: '||v_var3);
13.END;
output
v_var1: string literal
Compiled by Miliyon A 39
v_var2: 12.345
v_var3: 12.345
Make Use of Anchored Data-types
We have seen basic data types like number, varchar, boolean etcin PL
SQL we can declare variables with.
Consider the column esal for employee salary in the database and a
variable v_esal in the PL SQL program that calculates Net salary using
esal.
SYNTAX
SET SERVEROUTPUT ON
DECLARE
v_id employee.eid%type:='1234';
v_sal employee.esal%type;
BEGIN
IF v_sal>=7500 then
ELSE
DBMS_OUTPUT.PUT_LINE('Balance low');
END IF;
Compiled by Miliyon A 41
END;
Make Use of Anchored Data-types
SET SERVEROUTPUT ON
DECLARE
v_eid varchar(20):=&sv_eid;
BEGIN
SELECT eid, ename, etitle, esal INTO v_eid, v_ename, v_etitle, v_gs FROM employee WHERE eid=v_eid;
EXCEPTION
It specifies which statements(s) is executed first, which next and then which
till end.
Sequential: programs that contains statements that are executed one after the
other line by line. Every code we wrote so far is sequential in type.
Recursion is type
Compiled by Miliyon A of iteration. 43
Conditionals: conditions
Conditionals and: programs that contains statements based on conditions.
If statement
An IF statement has two forms: IF-THEN and IF-THEN-ELSE.
An IF-THEN statement allows you to specify only one group of actions to take.
In other words, this group of actions is taken only when a condition evaluates to TRUE.
An IF-THEN statement is the most basic kind of a conditional control; it has the following
structure:
IF CONDITION THEN
STATEMENT 1;
... STATEMENT N;
END IF;
Compiled by Miliyon A 44
Conditionals: conditions
The reserved word IF marks the beginning of the IF statement.
The word CONDITION between the keywords IF and THEN determines whether these
statements are executed.
END IF is a reserved phrase that indicates the end of the IF-THEN construct.
1. SET SERVEROUTPUT ON
2. DECLARE
3. v_id employee.eid%type:='1234';
4. v_sal employee.esal%type;
5. BEGIN
6. SELECT esal INTO v_sal FROM employee WHERE eid=v_id;
7. IF v_sal>=7500 then
8. DBMS_OUTPUT.PUT_LINE('I fetched this from Database: '||v_sal);
9. END IF;
10.DBMS_OUTPUT.PUT_LINE('Balance low');
11.Compiled
END; by Miliyon A 45
Conditionals: conditions
IF-THEN-ELSE STATEMENT
You should use the IF-THEN-ELSE construct when trying to choose between two
mutually exclusive actions.
STATEMENT 3;
Conditionals: conditions
IF-THEN-ELSE STATEMENT example: test if the number provided by the user is even
DECLARE
BEGIN
IF MOD(v_num,2) = 0 THEN
ELSE
END IF;
DBMS_OUTPUT.PUT_LINE ('Done');
END;
Compiled by Miliyon A 47
Solution
Conditionals: conditions
For the IF-THEN construct, the statements are not executed if an associated
condition evaluates to NULL. Next, control is passed to the first executable
statement after END IF.
For the IF-THEN-ELSE construct, the statements specified after the keyword ELSE
are executed if an associated condition evaluates to NULL.
DECLARE
v_num1 NUMBER := 0;
v_num2 NUMBER;
BEGIN
IF v_num1 = v_num2 THEN DBMS_OUTPUT.PUT_LINE ('v_num1 = v_num2');
ELSE DBMS_OUTPUT.PUT_LINE ('v_num1 != v_num2');
END IF;
Compiled by Miliyon A 48
END;
Conditionals: conditions
ELSIF Statements
ELSIF (or IF---ELSEIF…ELSE) statement is used when several mutually
exclusive statements are in the program.
Write a PL/SQL program that accepts students mark and convert it to grade
letters as per the grade scale given below and displays wrong mark entry for
mark out of the given ranges:
A=[85, 100]
B =[70, 85)
C=[50,70)
D=[40,50)
F=[0,40)
Here Is the
Compiled Solution
by Miliyon A 50
Conditionals: conditions
Write a PL/SQL program that accepts students mark and convert it to grade
letters as per the grade scale given below and displays wrong mark entry for
mark out of the given ranges:
A=[85, 100]
B =[70, 85)
C=[50,70)
D=[40,50)
F=[0,40)
Here Is the
Compiled Solution
by Miliyon A 51
Conditionals: conditions
Write a PL/SQL program that retrieve students gpa from students table and
rank students as per the Ranking scale given below:
Gpa>=3.25, Distniction
Gpa>2, Pass
Gpa<2, Poor
Here Is the
Compiled Solution
by Miliyon A 52
Conditional Control
CASE Statements
Compiled by Miliyon A 53
Conditional Control : CASE STATEMENT
CASE STATEMENTS
A CASE statement has the following structure:
Case selector
when expression 1 then statement 1;
when expression 2 then statement 2;
...
when expression n then statement n;
else statement n+1;
end case;
Compiled by Miliyon A 55
Conditional Control : CASE
STATEMENTS
CASE STATEMENTS
The reserved word CASE marks the start of the CASE statement.
The ELSE clause is optional and It works much like the ELSE clause
used in the IF-THEN-ELSE statement.
END CASE is a reserved phrase that indicates the end of the CASE
statement.
Compiled by Miliyon A 56
Conditional Control : CASE
STATEMENTS
CASE STATEMENTS
Note that the selector is evaluated only once, and the WHEN
clauses are evaluated sequentially.
Compiled by Miliyon A 58
Conditional Control : CASE
STATEMENTS
Example: Even Odd checker using CASE statement
1. DECLARE
2. v_num NUMBER := &sv_user_num;
3. v_num_flag NUMBER;
4. BEGIN
5. v_num_flag := MOD(v_num,2);
6. CASE v_num_flag
7. WHEN 0 THEN
8. DBMS_OUTPUT.PUT_LINE (v_num||’ is even number’);
9. ELSE
10.DBMS_OUTPUT.PUT_LINE (v_num||’ is odd number’);
11.END CASE;
12.DBMS_OUTPUT.PUT_LINE ('Done’);
13. END;
Compiled by Miliyon A 59
Conditional Control : SEARCHED CASE STATEMENTS
...
ELSE STATEMENT
Compiled by Miliyon A N+1; 60
Conditional Control : SEARCHED CASE STATEMENTS
DBMS_OUTPUT.PUT_LINE ('Done');
Conditional Control : SEARCHED CASE STATEMENTS
write a PL/SQL code (using searched) that accepts grade & credit hour and
calculates and Prints the GP for the course.
GP calculation Rules:
A=[80, 100]
B =[70, 80)
C=[50,70)
D=[40,50)
F=[0,40)
Solution
Compiled by Miliyon A 63
Conditional Control : SEARCHED CASE STATEMENTS
Update the course grade column for the student by the calculated grade
A=[80, 100]
B =[70, 80)
C=[50,70)
D=[40,50)
F=[0,40)
Solution
Compiled by Miliyon A 64
CASE VS SEARCHED CASE STATEMENTS
Compiled by Miliyon A 65
Case expression
An expression is statement that process & assigns some value to a variable.
The result of an expression yields a single value that is assigned to a
variable.
Compiled by Miliyon A 68
NULLIF and COALESCE Functions
THE NULLIF FUNCTION
The NULLIF function compares two expressions. If they are equal, the
function returns NULL; otherwise, it returns the value of the first
expression.
END;
Compiled by Miliyon A 70
NULLIF and COALESCE Functions
THE COALESCE FUNCTION
For example,
COALESCE (expression1, expression2)
is equivalent to
CASE
WHEN expression1 IS NOT NULL THEN expression1
ELSE expression2
END
Compiled by Miliyon A 72
NULLIF and COALESCE Functions
THE COALESCE FUNCTION
studresult.courseinstructorid,
studresult.enrollment,
COALESCE(studresult.courseinstructorid,
studresult.enrollment) Additional
Using a loop, you can write the desired number of records to a table.
1. simple loops,
2. WHILE loops,
The reserved word LOOP marks the beginning of the simple loop.
END LOOP is a reserved phrase that indicates the end of the loop
Compiled by Miliyon A 76
Iterative Control: Simple Loops
The basic structure of simple loop as you seen earlier doesn’t specify
when the loop terminates.
This program accepts the number of times from user and displays
“statement executed x times ” until
Compiled by Miliyon A 79
the specified number of times.
Iterative Control: Simple Loops
A simple loop example
1. SET SERVEROUTPUT ON
2. DECLARE
3. v Number:=&Numberoftimes;
4. d Number:=1;
5. BEGIN
6. LOOP
7. DBMS_OUTPUT.PUT_LINE ('statement executed'||d||'times
');
8. d:=d+1;
9. IF v=d then Exit;
10.END IF; END LOOP; END;
This program accepts the number of times from user and displays
“statement executed x times ” until
Compiled by Miliyon A 80
the specified number of times.
Iterative Control: Simple Loops
A simple loop examples
1. concatenateIDUsingLoop
2. CalculateGRD and UPDATE RECORD PLSQL.txt
Compiled by Miliyon A 81
Iterative Control: While Loops
A WHILE loop has the following structure:
while condition loop
statement 1;
statement 2;
... statement n;
end loop;
The reserved word WHILE marks the beginning of a loop construct.
The CONDITION is the loop condition that evaluates to TRUE or FALSE.
The result of this evaluation determines whether the loop is executed.
Statements 1 through N are a sequence of statements that is executed
repeatedly.
The END LOOP is a phrase that indicates the end of the loop construct.
Compiled by Miliyon A 82
Iterative Control:While Loops
example
SET SERVEROUTPUT ON
DECLARE
a Number:=0;
BEGIN
DBMS_OUTPUT.PUT_LINE (
a:=a+1;
END LOOP;
END;
Compiled by Miliyon A 83
Iterative Control: While Loops
A boolean valued variable can be used to control loop condition
DECLARE
v_test BOOLEAN := TRUE;
BEGIN
WHILE v_test LOOP
STATEMENTS;
IF TEST_CONDITION THEN
v_test := FALSE;
END IF;
END LOOP;
END;
The reserved word FOR marks the beginning of a FOR loop construct.
You don’t need to declare the loop counter in the declaration section.
They define the number of iterations for the loop, and their values are
evaluated once, for the first iteration of the loop.
At this point, it is determined how many times the loop will iterate.
END LOOP is a reserved phrase that marks the end of the loop construct.
86
Compiled by Miliyon A
The key word IN or IN REVERSE shows which way the loop counter begin
Iterative Control: Numeric FOR Loops
A for loop example:
For v_counter 1-5 (both limit values are included) the statement
v_counter = value is displayed.
Compiled by Miliyon A 87
Iterative Control: Numeric FOR Loops
A for loop example: Adding 1-5 to variable sum
1. set serveroutput on
2. declare
3. v_sum number:=0;// declared a variable for the sum
4. begin
5. for a in 1..5 loop // a between 1 and 5 IN
6. v_sum:=a + v_sum; //add a values to sum
7. if a=5 then //generate output only if a=5
8. dbms_output.put_line('the sum of the first '||a||'
integers is: '||v_sum);
9. end if; end loop; end;
END IF;
Iterative Control: the CONTINUE when statement
The continue and continue when statements are alternatives and can
be used interchangeably.
IF CONDITION THEN
CONTINUE;
END IF; is equivalent to CONTINUE WHEN CONDITION;
The CONTINUE and CONTINUE WHEN statements are valid only when
placed inside a loop.
When placed outside a loop, they cause a syntax error. To avoid this
error, use the RETURN statement .
Any type of LOOP can reside inside any other loop body.
In such cases we use terms outer loop to refer the hosting loop and
inner loop to refer the embraced loop.
For each iteration of the outer loop the whole iterations of the inner
loop are executed until its condition comes FALSE.
When the iterations of the inner loop are finished (when the inner
loop’s condition comes FALSE) the next iteration of the outerloop
begins and inner loop is executed wholly.
Compiled
Thebynested
Miliyon A LOOP terminates when
96 the outer loops condition comes
Iterative Control: Nested Loops
1. SET SERVEROUTPUT ON
2. BEGIN
3. for i IN 1..3 LOOP
4. for j in 1..3 LOOP
5. DBMS_OUTPUT.PUT_LINE(i||', '||j||‘ only j grow');
6. END LOOP;
7. DBMS_OUTPUT.PUT_LINE('First Value Incremented Now');
8. END LOOP;
9. END;
Compiled by Miliyon A 97
Iterative Control: Nested Loops
LOOP LABELS
When we work with Nested Loops sometimes the beginning and end of
loops might be confusing as the Nesting increases.
Compiled by Miliyon A 98
Iterative Control: Nested Loops
LOOP LABELS
Now look at our previous NESTED loop example, how much easier
to understand is it now?
1. SET SERVEROUTPUT ON
2. BEGIN
3. <<Outer_Loop>>
4. for i IN 1..3 LOOP
5. <<Inner_Loop>>
6. for j in 1..3 LOOP
7. DBMS_OUTPUT.PUT_LINE(i||', '||j||‘ only j grow');
8. END LOOP Inner_Loop;
9. DBMS_OUTPUT.PUT_LINE('First Value Incremented Now');
10. END LOOP Outer_Loop;
Compiled by Miliyon A 99
11.END;
Iterative Control: Nested Loops
END;
Error Handling and Exceptions
An example of exception handling for square root function
If input is negative number or text then the square root is not
defined.
1. DECLARE
2. v_num1 INTEGER := &sv_num1;
3. v_result NUMBER;
4. BEGIN
5. v_result := SQRT(v_num);
6. DBMS_OUTPUT.PUT_LINE ('v_result: '||v_result);
7. EXCEPTION
8. WHEN VALUE_ERROR THEN
9. DBMS_OUTPUT.PUT_LINE(‘Square Root of ‘||v_num1||’is
Undefined’);
10.END;
We can rewrite this code as follows:
IF num1>=0 THEN
v_result := SQRT(v_num);
Compiled by Miliyon A 105
DBMS_OUTPUT.PUT_LINE ('v_result: '||v_result);
Error Handling and Exceptions
SCOPE OF EXCEPTIONS
You define and use your own exceptions. For example what if an
integer variable you defined for student mark is 198? Built in
exceptions doesn’t know this.
In such cases you need to use your own program specific exceptions.