Oracle PLSQL Labbook
Oracle PLSQL Labbook
Oracle PL/SQL
Lab Book
Table of Contents
Document Revision History ................................................................................................ 2
Table of Contents ............................................................................................................... 3
Getting Started ................................................................................................................... 4
Overview ................................................................................................................ 4
Setup Checklist for Oracle 9i ................................................................................. 4
Instructions ............................................................................................................ 4
Learning More (Bibliography if applicable) ............................................................ 4
Lab 1. Introduction to Data Dictionary ............................................................................ 5
Lab 2. Introduction to PL/SQL and Cursors.................................................................... 6
Lab 3. Exception Handling and Dynamic SQL ............................................................... 8
Lab 4. Database Programming ..................................................................................... 10
Lab 5. Case Study 1 ..................................................................................................... 14
Lab 6. Case Study 2 ..................................................................................................... 16
Lab 7. Handling Files, DBMS_LOB .............................................................................. 18
Lab 8. SQL*Plus Reports.............................................................................................. 19
Lab 9. SQL Loader ....................................................................................................... 23
Appendices ....................................................................................................................... 28
Appendix A: Oracle Standards ............................................................................ 28
Appendix B: Coding Best Practices ..................................................................... 29
Appendix C: Table of Figures .............................................................................. 30
Appendix D: Table of Examples .......................................................................... 31
Getting Started
Overview
This lab book is a guided tour for learning Oracle 9i. It comprises ‘To Do’ assignments.
Follow the steps provided and work out the ‘To Do’ assignments.
Here is what is expected on your machine in order for the lab to work.
Minimum System Requirements
Intel Pentium 90 or higher (P166 recommended)
Microsoft Windows 95, 98, or NT 4.0, 2k, XP.
Memory: 32MB of RAM (64MB or more recommended)
Instructions
For all coding standards refer Appendix A. All lab assignments should refer
coding standards.
Create a directory by your name in drive <drive>. In this directory, create a
subdirectory Oracle 9i_assgn. For each lab exercise create a directory as lab
<lab number>.
Time 45 min
1.1: Get the details of all the database objects and their types created by the current
user.
1.2 Get the details of all the table names owned by current user
1.3 Get the details of table names and corresponding column names
1.4 Get the details of column names and corresponding constraint names
1.5: Get the details of the constraints and corresponding table name.
1.6: Get the details of all the View names and corresponding Text of the same.
1.7: Get the details of all the Sequence names and their last numbers reached so far.
1.8: Get the details of all the Synonym names and their parent object names.
2.1
DECLARE
V_Sample1 NUMBER(2);
V_Sample2 CONSTANT NUMBER(2) ;
V_Sample3 NUMBER(2) NOT NULL ;
V_Sample4 NUMBER(2) := 50;
V_Sample5 NUMBER(2) DEFAULT 25;
2.2
The following PL/SQL block is incomplete.
Modify the block to achieve requirements as stated in the comments in the block.
2.3. Write a PL/SQL block to retrieve all staff (code, name, salary) under specific
department number and display the result. (Note: The Department_Code will be accepted
from user. Cursor to be used.)
2.4. Write a PL/SQL block to increase the salary by 30 % or 5000 whichever minimum for
a given Department_Code.
2.5. Write a PL/SQL block to generate the following report for a given Department code
Note: Display suitable error massage if wrong department code has entered and if there
is no student in the given department.
For Grade:
Student should pass in each subject individually (pass marks 60).
Percent >= 80 then grade= A
Percent >= 70 and < 80 then grade= B
Percent >= 60 and < 70 then grade= C
Else D
2.6. Write a PL/SQL block to retrieve the details of the staff belonging to a particular
department. Department code should be passed as a parameter to the cursor.
3.2 The following PL/SQL block attempts to calculate bonus of staff for a given
MGR_CODE. Bonus is to be considered as twice of salary. Though Exception Handling
has been implemented but block is unable to handle the same.
Debug and verify the current behavior to trace the problem.
DECLARE
V_BONUS V_SAL%TYPE;
V_SAL STAFF_MASTER.STAFF_SAL%TYPE;
BEGIN
SELECT STAFF_SAL INTO V_SAL
FROM STAFF_MASTER
WHERE MGR_CODE=100006;
V_BONUS:=2*V_SAL;
DBMS_OUTPUT.PUT_LINE('STAFF SALARY IS ' || V_SAL);
DBMS_OUTPUT.PUT_LINE('STAFF BONUS IS ' || V_BONUS);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('GIVEN CODE IS NOT VALID.ENTER VALID CODE');
END;
3.4
Predict the output of the following block ? What corrections would be needed to make it
more efficient?
BEGIN
DECLARE
fname emp.ename%TYPE;
BEGIN
SELECT ename INTO fname
FROM emp
WHERE 1=2;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No data found in fname');
3.6: Write a PL/SQL program to check for the commission for an employee no 7369. If no
commission exists, then display the error message. Use Exceptions.
Note: Procedures and functions should handle validations, pre-defined oracle server and
user defined exceptions wherever applicable. Also use cursors wherever applicable.
4.1 Write a PL/SQL block to find the maximum salary of the staff in the given department.
Note: Department code should be passed as parameter to the cursor.
4.2. Write a function to compute age. The function should accept a date and return age in
years.
4.3. Write a procedure that accept staff code and update staff name to Upper case. If the
staff name is null raise a user defined exception.
4.4 Write a procedure to find the manager of a staff. Procedure should return the
following – Staff_Code, Staff_Name, Dept_Code and Manager Name.
4.5. Write a function to compute the following. Function should take Staff_Code and
return the cost to company.
DA = 15% Salary, HRA= 20% of Salary, TA= 8% of Salary.
Special Allowance will be decided based on the service in the company.
< 1 Year Nil
>=1 Year< 2 Year 10% of Salary
>=2 Year< 4 Year 20% of Salary
>4 Year 30% of Salary
4.6. Write a procedure that displays the following information of all staff
Note: - Status will be (Greater, Lesser or Equal) respective to average salary of their own
department. Display an error message Staff_Master table is empty if there is no matching
record.
4.7. Write a procedure that accept Staff_Code and update the salary and store the old
salary details in Staff_Master_Back (Staff_Master_Back has the same structure without
any constraint) table.
4.8. Create a procedure that accepts the book code as parameter from the user. Display
the details of the students/staff that have borrowed that book and has not returned the
same. The following details should be displayed
Function: This function will return years of experience for a staff. This function will take
the hiredate of the staff as an input parameter. The output will be rounded to the nearest
year (1.4 year will be considered as 1 year and 1.5 year will be considered as 2 year).
Procedure: Capture the value returned by the above function to calculate the additional
allowance for the staff based on the experience.
Additional Allowance = Year of experience x 3000
Calculate the additional allowance and store Staff_Code, Date of Joining, and Experience
in years and additional allowance in Staff_Allowance table.
4.10. Write a procedure to insert details into Book_Transaction table. Procedure should
accept the book code and staff/student code. Date of issue is current date and the
expected return date should be 10 days from the current date. If the expected return date
falls on Saturday or Sunday, then it should be the next working day.
4.11: Write a function named ‘get_total_records’, to pass the table name as a parameter,
and get back the number of records that are contained in the table. Test your function
with multiple tables.
4.12
Objective:The Procedure should update the salary of an employee and at the same time
retrieve the employee's name and new salary into PL/SQL variables.
4.13
The following procedure attempts to delete data from table passed as parameter.This
procedure has compilation errors. Identify and correct the problem.
4.14
Write a procedure which prints the following report using procedure:
The procedure should take deptno as user input and appropriately print the emp details.
Also display :
Figure 1 :Report
4.15: Write a query to view the list of all procedures ,functions and packages from the
Data Dictionary.
Customer_Masters
Account_Masters Table
Note: Account type can be either Savings (SAV) or Salary (SAL) account.
For savings account minimum amount should be 5000.
Transaction_Masters
5.1 Create appropriate Test Cases for the case study followed up by Self/Peer to Peer
Review and close any defects for the same.
5.2Write a procedure to accept customer name, address, and customer type and account
type. Insert the details into the respective tables.
5.3. Write a procedure to accept customer id, amount and the account number to which
the customer requires to transfer money. Following validations need to be done
Customer id should be valid
From account number should belong to that customer
To account number cannot be null but can be an account which need not exist in
account masters (some other account)
Adequate balance needs to be available for debit
5.4 Ensure all the Test cases defined are executed. Have appropriate Self/Peer to Peer
Code Review and close any defects for the same.
Consider the following table (myEmp) structure for the case study
EmpNo Ename City Designation Salary
-------------------------------------------------------------------
The following procedure accepts Task number and based on the same performs an
appropriate task.
PROCEDURE run_task (task_number_in IN INTEGER)
IS
BEGIN
IF task_number_in = 1
THEN
add_emp;
--should add new emps in myEmp.
--EmpNo should be inserted through Sequence.
--All other data to be taken as parameters.Default location is Mumbai.
END IF;
IF task_number_in = 2
THEN
raise_sal;
--should modify salary of an existing emp.
--should take new salary and empno as input parameters
--Should handle exception in case empno not found
--upper limit of rasing salary is 30%. should raise exception appropriately
END IF;
IF task_number_in = 3
THEN
remove_emp;
--should remove an existing emp
--should take empno as parameter
However ,it has been observed the method adopted in above procedure is inefficient.
6.1
Create appropriate Test Cases for the case study followed up by Self/Peer to Peer
Review and close any defects for the same.
6.2
Recreate the procedure (run_task) which is more efficient in performing the same.
6.3
Also, create relevant procedures (add_emp , raise_sal ,remove_emp)
with relevant logic (read comments)to verify the same.
6.5) Ensure all the Test cases defined are executed. Have appropriate Self/Peer to Peer
Code Review and close any defects for the same.
7.1: The following PL/SQL block creates file “TestFile.txt” with appropriate contents.
Enhance the block by reading the contents back from the file and displaying it at SQL
prompt.
Declare
TextHandler Utl_File.File_type;
WriteMessage Varchar2(400);
ReadMessage Varchar2(400);
Begin
TextHandler:=Utl_File.Fopen('d:\Sample','TestFile.txt','W');
WriteMessage:='FOPEN is a Function, which returns the value of type
File_Type \n UTL_file.PUT_LINE is a procedure in UTL_FILE, which write a line
to a file,Specific line terminator will be appended \n';
Utl_file.Putf(Texthandler,writemessage);
Utl_File.Fflush(Texthandler);
Utl_File.Fclose(Texthandler);
End;
/
7.2 Extend the implementation in the above block by incorporating Exception Handling.
7.3 We need to maintain the above block in database permanently.What can be done for
the same ? Rewrite the above to achieve the same.
7.4: Write a PL/SQL block to create a file “EmpDeptDetails.Txt” .The contents in the file
map to columns from both the tables Emp and Dept.
(Empno,Ename,Job, Sal, Dname, Loc)
Also read the contents back from the file and display it on prompt.
to insert space after the value changes in more than one ordered column
Then you must specify “multiple columns” and “actions” in a single BREAK command.
Now, to skip a page when the value of DEPARTMENT_ID changes, and to skip one line
when the value of JOB_ID changes, key in the following command:
Page: 1
DEPARTMENT_ID JOB_ID LAST_NAME SALARY
------------- ---------- ------------------------- ----------
20 MK_MAN Hartstein 13000
Page: 2
DEPARTMENT_ID JOB_ID LAST_NAME SALARY
------------- ---------- ------------------------- ----------
80 SA_MAN Russell 14000
Partners 13500
Page: 3
DEPARTMENT_ID JOB_ID LAST_NAME SALARY
------------- ---------- ------------------------- ----------
90 AD_PRES King 24000
6 rows selected.
Figure 2: Report
Step 2: Produce a report that does the following when the value of JOB_ID changes:
Additionally the report should do the following when the value of DEPT_ID changes:
The details should be displayed for all departments respective to jobs. (To Do)
******** ----------
sum 64300
-
-
-
-
-
25 rows selected.
Figure 3: Report
PERFECT WIDGETS
01-JAN-2008
PAGE: 1
COMPANY CONFIDENTIAL
6 rows selected.
20 MANAGER 3 $14,000.00
SALES 6 $11,000.00
30 CLERK 10 $13,500.00
MANAGER 3 $15,000.00
SALES 4 $10,000.00
40 PRESIDENT 1 424,000.00
.
.
.
----------
Grand Total of Sal: $98,560.00
Goals Use the SQL Loader utility and upload the given files under specified
conditions.
Time 1 hr
Step 1: Crosscheck for the relation. If it does not exist, create the Dept table.
Step 2: Create and save the control file named as ‘deptcontrol.ctl’ in the specified
location. Control file should contain following details:
12,RESEARCH,"SARATOGA"
10,"ACCOUNTING",CLEVELAND
11,"ART",SALEM
13,FINANCE,"BOSTON"
21,"SALES",PHILA.
22,"SALES",ROCHESTER
42,"INT'L","SAN FRAN
Step 3: Execute the SQL Loader command at the command prompt and verify the
updated Relation by issuing the command given below:
9.2: Use the SQL Loader utility. Upload the data file having Fixed-Format Fields, as
shown below, into Emp table.
Data file
Given below are a few sample data lines from the file ulcase2.dat.
Blank fields are automatically set to null.
7782 CLARK MANAGER 7839 2572.50 10
7839 KING PRESIDENT 5500.00 10
7934 MILLER CLERK 7782 920.00 10
7566 JONES MANAGER 7839 3123.75 20
7499 ALLEN SALESMAN 7698 1600.00 300.00 30
7654 MARTIN SALESMAN 7698 1312.50 1400.00 30
7658 CHAN ANALYST 7566 3450.00 20
7654 MARTIN SALESMAN 7698 1312.50 1400.00 30
Control file:
Datafile
A sample datafile used for this case, ulcase4.dat, is shown below. Asterisks are in the
first position. Further, a newline character, though not visible, is in position 20. Note that
clerk’s commission is -10, and SQL*Loader loads the value, converting it to a negative
number.
*7782 CLARK
MANAGER 7839 2572.50 -10 25 12-NOV-85
*7839 KING
PRESIDENT 5500.00 25 05-APR-83
*7934 MILLER
CLERK 7782 920.00 25 08-MAY-80
*7566 JONES
MANAGER 7839 3123.75 25 17-JUL-85
*7499 ALLEN
SALESMAN 7698 1600.00 300.00 25 3-JUN-84
*7654 MARTIN
SALESMAN 7698 1312.50 1400.00 25 21-DEC-85
*7658 CHAN
ANALYST 7566 3450.00 25 16-FEB-84
*CHEN
ANALYST 7566 3450.00 25 16-FEB-84
*7658 CHIN
ANALYST 7566 3450.00 25 16-FEB-84
1. REPLACE specifies that if there is data in the tables to be loaded (emp and proj),
SQL*loader should delete the data before loading new rows.
2. Multiple INTO TABLE clauses load two tables, emp and proj. The same set of
records is processed three times, using different combinations of columns each
time to load table proj.
3. WHEN loads only rows with nonblank project numbers. When projno is defined
as columns 25...27, rows are inserted into proj only if there is a value in those
columns.
4. When projno is defined as columns 29...31, rows are inserted into proj only if
there is a value in those columns.
5. When projno is defined as columns 33...35, rows are inserted into proj only if
there is a value in those columns.
Datafile:
9.5: Use SQL Loader utility to load specific data from the given flat file into the table. (To
Do)
The given flat file contains data in the form of DEPTNO, DEPTNAME, and LOCATION.
Using SQL Loader utility, load only DEPTNO and LOCATION from the .dat file into the
department table. Do not overwrite the source data present in department table.
Appendices
2. Prefix the table names with owner names, as this improves readability, and
avoids any unnecessary confusion.
2. Perform all your referential integrity checks and data validations by using
constraints (foreign key and check constraints). These constraints are faster than
triggers. So use triggers only for auditing, custom tasks, and validations that
cannot be performed by using these constraints.