Chapter 2 - PL SQL - updated
Chapter 2 - PL SQL - updated
Declarations of block 1
BEGIN
Executable Statements
Declarations of block 2
BEGIN
Executable Statements
EXCEPTION
Exception Handlers
declare
z emp%rowtype;
begin
select * into z from emp where empno='7369';
dbms_output.put_line(‘Emp ID:' || z.empno || ‘ – EMP
Name:' || z.ename);
end;
If – then statements
▪ If .. then, if .. then .. else, if .. then .. elsif
IF <condition> THEN
statements;
END IF;
declare
min_salary NUMBER := 5000;
begin
if min_salary > 3000 then
dbms_output.put_line(‘Min salary is higher than 3000’);
end if;
end;
If – then statements
▪ If .. then, if .. then .. else, if .. then .. elsif
IF < condition 1> THEN declare
statements 1; n NUMBER; result VARCHAR2(50);
begin
ELSE
if n = 0 then result:=‘Negative’
IF < condition 2> THEN
statements 2; else if n = 1 then result:=‘Positive’;
ELSE end if;
…..; end if;
END IF; dbms_output.put_line(‘The result is’ ||
END IF; result);
end;
If – then statements
▪ If .. then, if .. then .. else, if .. then .. elsif
IF < condition 1> THEN declare
statements 1; n NUMBER; result VARCHAR2(50);
begin
ELSIF < condition 2> THEN
if n = 0 then result:=‘Negative’
statements 2;
ELSIF < condition 3> THEN elsif n = 1 then result:=‘Positive’;
statements 3; end if;
END IF; dbms_output.put_line(‘The result is’ ||
result);
end;
Case statements
CASE [ expression ] select table_name,
WHEN condition_1 THEN result_1 TABLESPACE_NAME, CASE
WHEN condition_2 THEN result_2 owner
... WHEN 'SYS' THEN
WHEN condition_n THEN result_n 'The owner is SYS'
ELSE result WHEN 'SYSTEM' THEN
END 'The owner is SYSTEM'
ELSE 'The owner is another value'
END as Owner
from all_tables;
Case statements
CASE [ expression ] select table_name,
WHEN condition_1 THEN result_1 TABLESPACE_NAME, CASE
WHEN condition_2 THEN result_2 WHEN owner = 'SYS'
... THEN 'The owner is SYS'
WHEN condition_n THEN result_n WHEN owner = 'SYSTEM'
ELSE result THEN 'The owner is SYSTEM'
END
ELSE 'The owner is another value'
END as Owner
from all_tables;
Loop statements
LOOP declare
z number :=1;
<statements>
BEGIN
IF <stop_condition> THEN
LOOP
…. z :=z+5;
EXIT; IF (z>=100) THEN
END IF; exit;
END LOOP; End IF;
END LOOP;
END;
For … Loop statements
◼ Case 1:
FOR v IN [REVERSE] start_value .. end_value
LOOP
<statements>
END LOOP;
◼ Case 2:
FOR v IN (select statement)
LOOP
< statements > (… v.column1, v.column2 …)
For … Loop statements
◼ Case 1:
FOR v IN [REVERSE] start_value .. end_value
LOOP
<statements>
END LOOP;
--------
declare
z number:=1; i number;
BEGIN
FOR i IN 1 .. 10 LOOP
z :=z+3;
END LOOP;
END;
For … Loop statements
◼ Case 2:
FOR v IN (select statement)
LOOP
< statements > /*(… v.column1, v.column2 …) */
END LOOP;
declare
z number:=1; i number:=1;
BEGIN
WHILE (i<=10)
LOOP
i:=i+1; z :=z+3;
END LOOP;
END;
GOTO statements
▪ GOTO label_name
▪ Label_name: <<label_name>>
▪ Can not GOTO a label which stay in IF, CASE, LOOP statement
BEGIN
Dbms_output.put_line (‘Goto Test’);
GOTO Block1;
<Block1> Dbms_output.put_line (‘Good morning’); GOTO Block3;
<Block3> Dbms_output.put_line (‘Good afternoon’); GOTO Block2;
<Block2> Dbms_output.put_line (‘Good night’);
END;
EXCEPTION
▪ When an error occurs, an exception is raised, the program execution is
stopped, and control is transferred to the PL/SQL block containing the
exception handler.
▪ Implicit exceptions are raised, whereas user-defined exceptions are
raised explicitly using the RAISE statement.
▪ Predefined exceptions Example: ZERO_DIVIDE: A program attempts to
divide a number by zero.
https://docs.oracle.com/cd/B14117_01/appdev.101/b10807/07_errs.htm
EXCEPTION
https://docs.oracle.com/cd/B14117_01/appdev.101/b10807/07_errs.htm
NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a deleted
element in a nested table or an uninitialized element in an index-by table.
TOO_MANY_ROWS A SELECT INTO statement returns more than one row.
……………
EXCEPTION
DECLARE
sName Student.Name%TYPE;
StudentId number;
BEGIN
StudentId := &abc;
select Name into sName from Student where ID = StudentId;
dbms_output.put_line(sName);
EXCEPTION
WHEN NO_DATA_FOUND then
dbms_output.put_line (‘This student does not exist.’);
END;
EXCEPTION
▪ User defines exceptions
DECLARE
/*if Block of Function or Procedure then do not use Declare*/
Exception_Name EXCEPTION;
….
BEGIN
…
IF <error> then
RAISE Exception_Name ;
END IF ;
EXCEPTION
WHEN Exception_Name then
…..
WHEN OTHERS then
….
END;
EXCEPTION
▪ User defines exceptions
Create Function CheckStudentID (ID number) return number As
Dup_St_ID EXCEPTION;
BEGIN
IF ID=100 then
RAISE Dup_St_ID ;
ELSE
return 2;
END IF ;
EXCEPTION
WHEN Dup_St_ID then
return 1;
WHEN OTHERS then
return 0;
END;
----------
Select CheckStudentID (100) from Dual;
Select CheckStudentID (5) from Dual;
CURSOR
▪ A cursor is an object associated with a data table (as a pointer) and
allows the programmer to access with each row of the data table.
▪ A cursor is often used with return value of SQL statement
▪ Two types: explicit cursor, and implicit cursor
explicit cursor
CURSOR c_nv IS SELECT empno, sal FROM EMP
implicit cursor
Insert into EMP (empno, sal) values (7240, 1000)
IMPLICIT CURSOR
▪ is defined by Oracle
▪ Is created after SELECT INTO, INSERT, UPDATE, and DELETE
▪ SELECT…INTO is often used in case of implicit cursor
▪ SQL%ISOPEN, SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND are
used to get different values of cursor. Before executing the SQL statement,
the implicit cursor values are NULL.
▪ Raised an error when the query returns zero or multiple rows →
NO_DATA_FOUND or TOO_MANY_ROWS exception
IMPLICIT CURSOR
▪ Is created after SELECT INTO, INSERT, UPDATE, and DELETE
▪ SQL%ISOPEN, SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND are
used to get different values of cursor
Example 1: %NOTFOUND
SET SERVEROUTPUT ON
DELETE FROM emp WHERE empno=222;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE (‘Empno 222 does not exist');
END IF;
IMPLICIT CURSOR
▪ Is created after SELECT INTO, INSERT, UPDATE, and DELETE
▪ SQL%ISOPEN, SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND are
used to get different values of cursor
Example 2: SQL%FOUND
Example:
CURSUR cur_first is SELECT empno, sal FROM EMP WHERE dno=1
IF cur_first%ISOPEN THEN
FETCH cur_first INTO v_empno, v_sal;
ELSE
CLOSE cur_first;
END IF;
EXPLICIT CURSOR
%NOTFOUND: NULL (before first fetch), FALSE (fetched successfully),
TRUE (no row returned), INVALID_CURSOR (not opened)
Example:
CURSOR cur_first (v_eno EMP.empno%TYPE) IS
SELECT empno, sal
FROM EMP
WHERE empno= v_eno;
RETURN day;
END;
FUNCTION
FUNCTION Day_Display (n NUMBER) RETURN CHAR
------
declare
x char(30); y number;
begin
dbms_output.put_line (‘Function with parameters testing');
y:=4;
x:= Day_Display (y);
dbms_output.put_line (y);
dbms_output.put_line (x);
end;
FUNCTION
CREATE FUNCTION MedicalTest_Display (n NUMBER, m OUT NUMBER) RETURN VARCHAR
AS
result VARCHAR2(50);
BEGIN
if n = 0 then result:=‘Negative’
else if n = 1 then result:=‘Positive’;
else m = 0;
end if;
end if;
RETURN result;
END;
FUNCTION
FUNCTION MedicalTest_Display (n NUMBER, m OUT NUMBER) RETURN VARCHAR
------
declare
x varchar(30); y number; z number;
begin
dbms_output.put_line (‘Function with parameters testing');
y:=1;
x:= MedicalTest_Display (y, z);
dbms_output.put_line (x);
dbms_output.put_line (z);
end;
PROCEDURE
▪ Execute block
CREATE [OR REPLACE] PROCEDURE function_name [(argument1 [, argument2,…])]
IS
[variable declare]
BEGIN
<Statements>
[EXCEPTION <exception>]
END;
- OR REPLACE: automatically deletes and creates a new function if the function
name already exists.
- argument [IN | OUT | IN OUT] datatype [{ := | DEFAULT value}]
PROCEDURE
CREATE PROCEDURE Day_Display (n NUMBER)
AS
day CHAR(15);
BEGIN
IF n =1 THEN day :='Sunday’;
ELSIF n =2 THEN day :='Monday’;
ELSIF n =3 THEN day :='Tuesday’;
ELSIF n =4 THEN day :='Wednesday’;
ELSIF n =5 THEN day :='Thursday’;
ELSIF n =6 THEN day :='Friday’;
ELSIF n =7 THEN day :='Saturday';
END IF;
END;
----------------
Day_Display (1);
Relational data model example
1. EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary,
Super_ssn, Dno)
2. DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
3. DEPT_LOCATIONS (Dnumber, Dlocation)
4. PROJECT (Pnumber, Pname, Plocation, Dnum)
5. WORKS_ON (Essn, Pno, Hours)
6. DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship)
Relational data model example
Relational data model example
1. Show information of employee works on project. The information
including Ssn, Fname, Lname, Pname, Dnum (department managed
the project), Hour, Note (if the hour >30, note := ‘Hard’, else note :=
‘Normal’)
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
DEPT_LOCATIONS (Dnumber, Dlocation)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship)
Relational data model example
2. Show information of department 1’s employees worked on project.
The information including Ssn, Fname, Lname, Pname, Dnum
(department managed the project), Hour, Note (if the hour >30,
note := ‘Hard’, else note := ‘Normal’)
Note: Display the name of the department 1 first; Display the list of
employee meet requirements
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
DEPT_LOCATIONS (Dnumber, Dlocation)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship)
Relational data model example
3. Show information of department’s employees worked on project.
The information including Ssn, Fname, Lname, Pname, Dnum
(department managed the project), Hour, Note (if the hour >30,
note := ‘Hard’, else note := ‘Normal’)
Note: Use department number as a parameter of a cursor
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
DEPT_LOCATIONS (Dnumber, Dlocation)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship)
Q A