SlideShare a Scribd company logo
1 of 17
PLSQL:

1)
Write a PL/SQL block to accept a year input and check whether it is a leap year.

DECLARE
v_YEAR NUMBER(4) := &P_YEAR;
v_REMAINDER1 NUMBER(5,2);
v_REMAINDER2 NUMBER(5,2);
v_REMAINDER3 NUMBER(5,2);
BEGIN
v_REMAINDER1 := MOD(v_YEAR,4);
v_REMAINDER2 := MOD(v_YEAR,100);
v_REMAINDER3 := MOD(v_YEAR,400);
IF ((v_REMAINDER1 = 0 AND v_REMAINDER2 <> 0 ) OR
v_REMAINDER3 = 0) THEN
DBMS_OUTPUT.PUT_LINE(v_YEAR || ' is a leap year');
ELSE
DBMS_OUTPUT.PUT_LINE(v_YEAR || ' is not a leap
year');
END IF;
END;

2)
Write a PL/SQL block which will accept the employee number and print the annual_salary as well as
the bonus.
 The PL/SQL block should:
   Calculate the annual salary as salary * 12
   Calculate the bonus as indicated in the following table:
 Annual Salary      Bonus
>= 20,000           2000
19,999–10,000       1000
<= 9,999            500

DECLARE
V_EMP_ID NUMBER := &EMPLOYEE_ID;
V_SAL NUMBER(7,2);
V_BONUS NUMBER(7,2);
V_ANN_SALARY NUMBER(15,2);
BEGIN

SELECT SALARY INTO V_SAL FROM EMPLOYEES WHERE EMPLOYEE_ID =
V_EMP_ID;

V_ANN_SALARY := V_SAL * 12;
DBMS_OUTPUT.PUT_LINE('Annual Salary is : '||V_ANN_SALARY);
IF V_ANN_SALARY >= 20000 THEN
V_BONUS := 2000;
ELSIF V_ANN_SALARY <= 19999 AND V_ANN_SALARY >=10000 THEN
V_BONUS := 1000;
ELSE
V_BONUS := 500;
END IF;
DBMS_OUTPUT.PUT_LINE ('The Bonus is $ ' || TO_CHAR(V_BONUS));
END;


3)
Declare a cursor named EMP_CUR to select the employee’s last name, salary, and hire
date from the EMPLOYEES table
Process each row from the cursor, and if the salary is greater than 15,000 and the hire
date is later than 01-FEB-1988, display the employee name, salary, and hire date in
the format shown in the following sample output:




DECLARE
CURSOR C_EMP_CUR IS
SELECT last_name,salary,hire_date FROM EMPLOYEES;
V_ENAME VARCHAR2(25);
v_SAL NUMBER(7,2);
V_HIREDATE DATE;
BEGIN
OPEN C_EMP_CUR;
FETCH C_EMP_CUR INTO V_ENAME,V_SAL,V_HIREDATE;
WHILE C_EMP_CUR%FOUND
LOOP
IF V_SAL > 15000 AND V_HIREDATE >=
TO_DATE('01-FEB-1988','DD-MON-YYYY') THEN
DBMS_OUTPUT.PUT_LINE (V_ENAME || ' earns '
|| TO_CHAR(V_SAL)|| ' and joined the organization on '
|| TO_DATE(V_HIREDATE,'DD-Mon-YYYY'));
END IF;
FETCH C_EMP_CUR INTO V_ENAME,V_SAL,V_HIREDATE;
END LOOP;
CLOSE C_EMP_CUR;
END;
4)
Create a PL/SQL block to retrieve and output the last name and department ID of each employee from the EMPLOYEES
table for those employees whose EMPLOYEE_ID is less than 115.
In the PL/SQL block, use a cursor FOR loop strategy instead of the OPEN / FETCH /CLOSE cursor methods used in the
previous practice.
1. In the declarative section:
• Create two associative arrays. The unique key column for both arrays should be of the BINARY INTEGER data type. One
array holds the employee’s last name and the other holds the department ID.
• Declare a counter variable to be used in the executable section
• Declare a cursor that selects the last name and department ID for employees whose ID is less than 115

DECLARE
TYPE Table_Ename IS table of employees.last_name%TYPE
INDEX BY BINARY_INTEGER;
TYPE Table_dept IS table of employees.department_id%TYPE
INDEX BY BINARY_INTEGER;
Tename Table_Ename;
Tdept Table_dept;
i BINARY_INTEGER :=0;
CURSOR Namedept IS SELECT last_name,department_id
FROM employees WHERE employee_id < 115;
BEGIN
FOR emprec in Namedept
LOOP
i := i +1;
Tename(i) := emprec.last_name;
Tdept(i) := emprec.department_id;
DBMS_OUTPUT.PUT_LINE ('Employee: ' || Tename(i) ||
' is in department number: ' || Tdept(i));
END LOOP;
END;



5)
Create a table:
CREATE TABLE analysis
(ename Varchar2(20), years Number(2), sal Number(8,2)
);

Write a PL/SQL block that handles an exception, as follows:
1. Declare variables for the employee last name, salary, and hire date. Use a substitution
variable for the employee last name. Then, query the employees table for the
last_name, salary, and hire_date of the specified employee.
2. If the employee has been with the organization for more than five years, and if that
employee’s salary is less than 3,500, raise an exception. In the exception handler,
perform the following:
• Output the following information: employee last name and the message “due
for a raise,” similar to the following:
Insert the last name, years of service, and salary into the analysis table.

3. If there is no exception, output the employee last name and the message “not due for a raise,” similar to the following:




Verify the results by querying the analysis table. Use the following test cases to test the PL/SQL block.
LAST_NAME MESSAGE
Austin             Not due for a raise
Nayer              Due for a raise
Fripp              Not due for a raise
Khoo               Due for a raise

SET SERVEROUTPUT ON;
DECLARE
E_DUE_FOR_RAISE EXCEPTION;
V_HIREDATE EMPLOYEES.HIRE_DATE%TYPE;
V_ENAME EMPLOYEES.LAST_NAME%TYPE := INITCAP( '& B_ENAME');
V_SAL EMPLOYEES.SALARY%TYPE;
V_YEARS NUMBER(2);
BEGIN
SELECT LAST_NAME,SALARY,HIRE_DATE
INTO V_ENAME,V_SAL,V_HIREDATE
FROM employees WHERE last_name = V_ENAME;
V_YEARS := MONTHS_BETWEEN(SYSDATE,V_HIREDATE)/12;
IF V_SAL < 3500 AND V_YEARS > 5 THEN
RAISE E_DUE_FOR_RAISE;
ELSE
DBMS_OUTPUT.PUT_LINE (' not due for a raise');
END IF;
EXCEPTION
WHEN E_DUE_FOR_RAISE THEN
BEGIN
DBMS_OUTPUT.PUT_LINE (V_NAME || ' due for a raise');
INSERT INTO ANALYSIS(ENAME,YEARS,SAL)
VALUES (V_ENAME,V_YEARS,V_SAL);
END;
END;
/
SELECT * FROM analysis;

6)
Create, compile, and invoke the ADD_JOB procedure and review the results.
a) Create a procedure called ADD_JOB to insert a new job into the JOBS table.
Provide the ID and job title using two parameters.
Note: You can create the procedure (and other objects) by entering the code in the
SQL Worksheet area, and then click the Run Script (F5) icon. This creates and
compiles the procedure. To find out whether or not the procedure has any errors,
click the procedure name in the procedure node, and then select Compile from the
pop-up menu.
b) Invoke the procedure with IT_DBA as the job ID and Database
Administrator as the job title. Query the JOBS table and view the results.
c) Invoke your procedure again, passing a job ID of ST_MAN and a job title of
Stock Manager. What happens and why?

a)
CREATE OR REPLACE PROCEDURE add_job(
p_jobid jobs.job_id%type,
p_jobtitle jobs.job_title%type) IS
BEGIN
  INSERT INTO job(job_id, job_title)
  VALUES(p_jobid, p_jobtitle);
  COMMIT;
END add_job;
/

b)
EXECUTE add_job('IT_DBA', 'Database Administrator');

SELECT * FROM jobs;

c)
An exception occurs because there is a Unique key integrity constraint on the
JOB_ID column.


7)

7a. Create a procedure called UPD_JOB to update the job title. Provide the job ID and
a new title using two parameters. Include the necessary exception handling if no
update occurs.
CREATE OR REPLACE PROCEDURE upd_job(
p_jobid jobs.job_id%type,
p_jobtitle jobs.job_title%type) IS
BEGIN
  UPDATE job
  SET job_title = p_jobtitle
 WHERE job_id = p_jobid;

 IF sql%NOTFOUND THEN
  RAISE_APPLICATION_ERROR(-20000, 'No job updated');
 ELSE
 COMMIT;
END IF;
END upd_job;
/

7b) Invoke the procedure to change the job title of the job ID IT_DBA to Data Administrator. Query the JOBS table and
view the results.

EXECUTE add_job('IT_DBA', 'Data Administrator');

SELECT * FROM jobs;

7c) Test the exception-handling section of the procedure by trying to update a job that does not exist. You can use the job ID
IT_WEB and the job title Web Master.

EXECUTE upd_job('IT_WEB', 'Web Master');

SELECT * FROM jobs where job_id = 'IT_WEB';


8) Create a procedure called GET_EMPLOYEE to query the EMPLOYEES table, retrieving the salary and job ID for an
employee when provided with the employee ID.
a) Create a procedure that returns a value from the SALARY and JOB_ID columns for a specified employee ID. Remove
syntax errors, if any, and then recompile the code.


9)
Create and invoke the GET_JOB function to return a job title.
9a) Create and compile a function called GET_JOB to return a job title.

CREATE OR REPLACE FUNCTION get_job (p_jobid IN
jobs.job_id%type)
RETURN jobs.job_title%type IS
v_title jobs.job_title%type;
BEGIN
SELECT job_title
INTO v_title
FROM jobs
WHERE job_id = p_jobid;
RETURN v_title;
END get_job;
/

9b)Create a VARCHAR2 host variable called b_title, allowing a length of 35
characters. Invoke the function with job ID SA_REP to return the value in the
host variable, and then print the host variable to view the result.

VARIABLE b_title VARCHAR2(35)
EXECUTE :b_title := get_job ('SA_REP');
PRINT b_title
10) Create a function called GET_ANNUAL_COMP to return the annual salary computed
from an employee’s monthly salary and commission passed as parameters.
10 a) Create the GET_ANNUAL_COMP function, which accepts parameter values for the
monthly salary and commission. Either or both values passed can be NULL, but
the function should still return a non-NULL annual salary. Use the following basic
formula to calculate the annual salary:
(salary*12) + (commission_pct*salary*12)

CREATE OR REPLACE FUNCTION get_annual_comp(
p_sal IN employees.salary%TYPE,
p_comm IN employees.commission_pct%TYPE)
RETURN NUMBER IS
BEGIN
RETURN (NVL(p_sal,0) * 12 + (NVL(p_comm,0) * nvl(p_sal,0)
* 12));
END get_annual_comp;
/

10b) Use the function in a SELECT statement against the EMPLOYEES table for
employees in department 30.

SELECT employee_id, last_name,
get_annual_comp(salary,commission_pct) "Annual
Compensation"
FROM employees
WHERE department_id=30
/

11)
Create a procedure, ADD_EMPLOYEE, to insert a new employee into the
EMPLOYEES table. The procedure should call a VALID_DEPTID function to check
whether the department ID specified for the new employee exists in the
DEPARTMENTS table.
11a) Create a function called VALID_DEPTID to validate a specified department ID
and return a BOOLEAN value of TRUE if the department exists.

CREATE OR REPLACE FUNCTION valid_deptid(
p_deptid IN departments.department_id%TYPE)
RETURN BOOLEAN IS
v_dummy PLS_INTEGER;
BEGIN
SELECT 1
INTO v_dummy
FROM departments
WHERE department_id = p_deptid;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END valid_deptid;
11b) Create the ADD_EMPLOYEE procedure to add an employee to the EMPLOYEES
table. The row should be added to the EMPLOYEES table if the VALID_DEPTID
function returns TRUE; otherwise, alert the user with an appropriate message.
Provide the following parameters:
- first_name
- last_name
- email
- job: Use 'SA_REP' as the default.
- mgr: Use 145 as the default.
- sal: Use 1000 as the default.
- comm: Use 0 as the default.
- deptid: Use 30 as the default.
- Use the EMPLOYEES_SEQ sequence to set the employee_id column.
    − Set the hire_date column to TRUNC(SYSDATE).

CREATE OR REPLACE PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT
'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30)
IS
BEGIN
IF valid_deptid(p_deptid) THEN
INSERT INTO employees(employee_id, first_name,
last_name, email,job_id, manager_id, hire_date, salary, commission_pct,
department_id)
VALUES (employees_seq.NEXTVAL, p_first_name,
p_last_name, p_email,
p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm,
p_deptid);
ELSE
RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID.
Try again.');
END IF;
END add_employee;


11c) Call ADD_EMPLOYEE for the name 'Jane Harris' in department 15,
leaving other parameters with their default values. What is the result?

EXECUTE add_employee('Jane', 'Harris', 'JAHARRIS', p_deptid=> 15);

11d) Add another employee named Joe Harris in department 80, leaving the remaining
parameters with their default values. What is the result?
EXECUTE add_employee('Joe', 'Harris', 'JAHARRIS',
p_deptid=> 80)
12)
1) Create a package specification and body called JOB_PKG, containing a copy of your
ADD_JOB, UPD_JOB, and DEL_JOB procedures as well as your GET_JOB function.
Note: Use the code from your previously saved procedures and functions when
creating the package. You can copy the code in a procedure or function, and then
paste the code into the appropriate section of the package.
a) Create the package specification including the procedures and function headings
as public constructs.

CREATE OR REPLACE PACKAGE job_pkg IS
PROCEDURE add_job (p_jobid jobs.job_id%TYPE, p_jobtitle
jobs.job_title%TYPE);
PROCEDURE del_job (p_jobid jobs.job_id%TYPE);
FUNCTION get_job (p_jobid IN jobs.job_id%type) RETURN
jobs.job_title%type;
PROCEDURE upd_job(p_jobid IN jobs.job_id%TYPE, p_jobtitle
IN jobs.job_title%TYPE);
END job_pkg;
/
SHOW ERRORS

b) Create the package body with the implementations for each of the subprograms.
CREATE OR REPLACE PACKAGE BODY job_pkg IS
PROCEDURE add_job (
p_jobid jobs.job_id%TYPE,
p_jobtitle jobs.job_title%TYPE) IS
BEGININSERT INTO jobs (job_id, job_title)
VALUES (p_jobid, p_jobtitle);
COMMIT;
END add_job;
PROCEDURE del_job (p_jobid jobs.job_id%TYPE) IS
BEGIN
DELETE FROM jobs
WHERE job_id = p_jobid;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20203, 'No jobs
deleted.');
END IF;
END DEL_JOB;
FUNCTION get_job (p_jobid IN jobs.job_id%type)
RETURN jobs.job_title%type IS
v_title jobs.job_title%type;
BEGIN
SELECT job_title
INTO v_title
FROM jobs
WHERE job_id = p_jobid;
RETURN v_title;
END get_job;
PROCEDURE upd_job(
p_jobid IN jobs.job_id%TYPE,
p_jobtitle IN jobs.job_title%TYPE) IS
BEGIN
UPDATE jobs
SET job_title = p_jobtitle
WHERE job_id = p_jobid;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20202, 'No job updated.');
END IF;
END upd_job;
END job_pkg;
/

c) Invoke your ADD_JOB package procedure by passing the values IT_SYSAN and
SYSTEMS ANALYST as parameters.

EXECUTE job_pkg.add_job('IT_SYSAN', 'Systems Analyst');


13)
Create and invoke a package that contains private and public constructs.
a) Create a package specification and a package body called EMP_PKG that contains
the following procedures and function that you created earlier:
i) ADD_EMPLOYEE procedure as a public construct
ii) GET_EMPLOYEE procedure as a public construct
     iii) VALID_DEPTID function as a private construct

CREATE OR REPLACE PACKAGE emp_pkg IS
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30);
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE);
END emp_pkg;
/
CREATE OR REPLACE PACKAGE BODY emp_pkg IS
FUNCTION valid_deptid(p_deptid IN
departments.department_id%TYPE) RETURN BOOLEAN IS
v_dummy PLS_INTEGER;
BEGIN
SELECT 1
INTO v_dummy
FROM departments
WHERE department_id = p_deptid;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END valid_deptid;

PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30) IS
BEGIN
IF valid_deptid(p_deptid) THEN
INSERT INTO employees(employee_id, first_name,
last_name, email,
job_id, manager_id, hire_date, salary,
commission_pct, department_id)
VALUES (employees_seq.NEXTVAL, p_first_name,
p_last_name, p_email,
p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm,
p_deptid);
ELSE
RAISE_APPLICATION_ERROR (-20204, 'Invalid
department ID. Try again.');
END IF;
END add_employee;
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE) IS
BEGIN
SELECT salary, job_id
INTO p_sal, p_job
FROM employees
WHERE employee_id = p_empid;
END get_employee;
END emp_pkg;
/

b) Invoke the EMP_PKG.ADD_EMPLOYEE procedure, using department ID 15 for
employee Jane Harris with the email ID JAHARRIS. Because department ID 15
does not exist, you should get an error message as specified in the exception
handler of your procedure.
EXECUTE emp_pkg.add_employee('Jane', 'Harris','JAHARRIS',
p_deptid => 15);

c) Invoke the ADD_EMPLOYEE package procedure by using department ID 80 for
employee David Smith with the email ID DASMITH.

EXECUTE emp_pkg.add_employee('David', 'Smith','DASMITH',
p_deptid => 80);

14)
modify the code for the EMP_PKG package that you created earlier,
and then overload the ADD_EMPLOYEE procedure. Next, you create two overloaded
functions called GET_EMPLOYEE in the EMP_PKG package. You also add a public
procedure to EMP_PKG to populate a private PL/SQL table of valid department IDs and
modify the VALID_DEPTID function to use the private PL/SQL table contents to
validate department ID values. You also change the VALID_DEPTID validation
processing function to use the private PL/SQL table of department IDs. Finally, you
reorganize the subprograms in the package specification and the body so that they are in
alphabetical sequence.
1) Modify the code for the EMP_PKG package that you created in Practice 4 step 2, and
overload the ADD_EMPLOYEE procedure.
a) In the package specification, add a new procedure called ADD_EMPLOYEE that
accepts the following three parameters:
i) First name
ii) Last name
     iii) Department ID

CREATE OR REPLACE PACKAGE emp_pkg IS
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30);
/* New overloaded add_employee */
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_deptid employees.department_id%TYPE);
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE);
END emp_pkg;

b) Implement the new ADD_EMPLOYEE procedure in the package body as follows:
i) Format the email address in uppercase characters, using the first letter of the
first name concatenated with the first seven letters of the last name.
ii) The procedure should call the existing ADD_EMPLOYEE procedure to perform
the actual INSERT operation using its parameters and formatted email to
supply the values.
     iii) Click Run Script to create the package. Compile the package.

CREATE OR REPLACE PACKAGE BODY emp_pkg IS
FUNCTION valid_deptid(p_deptid IN
departments.department_id%TYPE) RETURN BOOLEAN IS
v_dummy PLS_INTEGER;
BEGIN
SELECT 1
INTO v_dummy
FROM departments
WHERE department_id = p_deptid;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END valid_deptid;
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30) IS
BEGIN
IF valid_deptid(p_deptid) THEN
INSERT INTO employees(employee_id, first_name, last_name,
email, job_id, manager_id, hire_date, salary,
commission_pct, department_id)
VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name,
p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm,
p_deptid);
ELSE
RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try
again.');
END IF;
END add_employee;
/* New overloaded add_employee procedure */
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_deptid employees.department_id%TYPE) IS
p_email employees.email%type;
BEGIN
p_email := UPPER(SUBSTR(p_first_name, 1,
1)||SUBSTR(p_last_name, 1, 7));
add_employee(p_first_name, p_last_name, p_email, p_deptid =>
p_deptid);
END;
/* End declaration of the overloaded add_employee procedure */
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE) IS
BEGIN
SELECT salary, job_id
INTO p_sal, p_job
FROM employees
WHERE employee_id = p_empid;
END get_employee;
END emp_pkg;
/

c) Invoke the new ADD_EMPLOYEE procedure using the name Samuel Joplin
to be added to department 30.

EXECUTE emp_pkg.add_employee('Samuel', 'Joplin', 30);


15)
In the EMP_PKG package, create two overloaded functions called GET_EMPLOYEE:
15a) In the package specification, add the following functions:
i) The GET_EMPLOYEE function that accepts the parameter called p_emp_id
based on the employees.employee_id%TYPE type. This function
should return EMPLOYEES%ROWTYPE.
ii) The GET_EMPLOYEE function that accepts the parameter called
p_family_name of type employees.last_name%TYPE. This function
should return EMPLOYEES%ROWTYPE.

CREATE OR REPLACE PACKAGE emp_pkg IS
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30);
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_deptid employees.department_id%TYPE);
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE);
/* New overloaded get_employees functions specs starts here: */
FUNCTION get_employee(p_emp_id employees.employee_id%type)
return employees%rowtype;
FUNCTION get_employee(p_family_name employees.last_name%type)
return employees%rowtype;
/* New overloaded get_employees functions specs ends here. */
END emp_pkg;

15 b)
In the package body:
i) Implement the first GET_EMPLOYEE function to query an employee using the
employee’s ID.
ii) Implement the second GET_EMPLOYEE function to use the equality operator
on the value supplied in the p_family_name parameter
CREATE OR REPLACE PACKAGE emp_pkg IS
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30);
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_deptid employees.department_id%TYPE);
PROCEDURE get_employee(p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE);
/* New overloaded get_employees functions specs starts here: */
FUNCTION get_employee(p_emp_id employees.employee_id%type)
return employees%rowtype;
FUNCTION get_employee(p_family_name employees.last_name%type)
return employees%rowtype;
/* New overloaded get_employees functions specs ends here. */
END emp_pkg;

-- package body
CREATE OR REPLACE PACKAGE BODY emp_pkg IS
FUNCTION valid_deptid(p_deptid IN
departments.department_id%TYPE) RETURN BOOLEAN IS
v_dummy PLS_INTEGER;
BEGIN
SELECT 1
INTO v_dummy
FROM departments
WHERE department_id = p_deptid;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END valid_deptid;
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 30) IS
BEGIN
IF valid_deptid(p_deptid) THEN
INSERT INTO employees(employee_id, first_name, last_name,
email, job_id, manager_id, hire_date, salary,
commission_pct, department_id)
VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name,
p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm,
p_deptid);
ELSE
RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID.
Try again.');
END IF;
END add_employee;
PROCEDURE add_employee(
p_first_name employees.first_name%TYPE,
p_last_name employees.last_name%TYPE,
p_deptid employees.department_id%TYPE) IS
p_email employees.email%type;
BEGIN
p_email := UPPER(SUBSTR(p_first_name, 1,
1)||SUBSTR(p_last_name, 1, 7));
add_employee(p_first_name, p_last_name, p_email, p_deptid =>
p_deptid);
END;
PROCEDURE get_employee(
p_empid IN employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE) IS
BEGIN
SELECT salary, job_id
INTO p_sal, p_job
FROM employees
WHERE employee_id = p_empid;
END get_employee;
/* New get_employee function declaration starts here */
FUNCTION get_employee(p_emp_id employees.employee_id%type)
return employees%rowtype IS
rec_emp employees%rowtype;
BEGIN
SELECT * INTO rec_emp
FROM employees
WHERE employee_id = p_emp_id;
RETURN rec_emp;
END;
FUNCTION get_employee(p_family_name employees.last_name%type)
return employees%rowtype IS
rec_emp employees%rowtype;
BEGIN
SELECT * INTO rec_emp
FROM employees
WHERE last_name = p_family_name;
RETURN rec_emp;
END;
/* New overloaded get_employee function declaration ends here */
END emp_pkg;


  16) Example for utl_file package:
CREATE OR REPLACE PROCEDURE employee_report(
p_dir IN VARCHAR2, p_filename IN VARCHAR2) IS
f UTL_FILE.FILE_TYPE;
CURSOR cur_avg IS
SELECT last_name, department_id, salary
FROM employees outer
WHERE salary > (SELECT AVG(salary)
FROM employees inner
GROUP BY outer.department_id)
ORDER BY department_id;
BEGIN
f := UTL_FILE.FOPEN(p_dir, p_filename,'W');
UTL_FILE.PUT_LINE(f, 'Employees who earn more than average
salary: ');
UTL_FILE.PUT_LINE(f, 'REPORT GENERATED ON ' ||SYSDATE);
UTL_FILE.NEW_LINE(f);
FOR emp IN cur_avg
LOOP
UTL_FILE.PUT_LINE(f,
RPAD(emp.last_name, 30) || ' ' ||
LPAD(NVL(TO_CHAR(emp.department_id,'9999'),'-'), 5) || ' '
||
LPAD(TO_CHAR(emp.salary, '$99,999.00'), 12));
END LOOP;
UTL_FILE.NEW_LINE(f);
UTL_FILE.PUT_LINE(f, '*** END OF REPORT ***');
UTL_FILE.FCLOSE(f);
END employee_report;

More Related Content

What's hot

Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
Achmad Solichin
 
Pl sql student guide v 4
Pl sql student guide v 4Pl sql student guide v 4
Pl sql student guide v 4
Nexus
 

What's hot (20)

10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Ref cursor
Ref cursorRef cursor
Ref cursor
 
Sql task answers
Sql task answersSql task answers
Sql task answers
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Les01
Les01Les01
Les01
 
Sql task
Sql taskSql task
Sql task
 
Pl sql student guide v 4
Pl sql student guide v 4Pl sql student guide v 4
Pl sql student guide v 4
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 
All payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion CloudAll payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion Cloud
 
Setting up audits and audit reports Fusion Cloud
Setting up audits and audit reports Fusion Cloud Setting up audits and audit reports Fusion Cloud
Setting up audits and audit reports Fusion Cloud
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 
Oracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions QueryOracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions Query
 
Cursores.ppt
Cursores.pptCursores.ppt
Cursores.ppt
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 

Viewers also liked

Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
vijaybusu
 
Practice create procedure
Practice   create procedurePractice   create procedure
Practice create procedure
cit gubbi
 
Mc amca04919 plsql programs
Mc amca04919 plsql programsMc amca04919 plsql programs
Mc amca04919 plsql programs
Ashwin Kumar
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
Ashwin Kumar
 
Sql Queries
Sql QueriesSql Queries
Sql Queries
webicon
 
Pl sql student guide v 3
Pl sql student guide v 3Pl sql student guide v 3
Pl sql student guide v 3
Nexus
 

Viewers also liked (20)

Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Plsql programs(encrypted)
Plsql programs(encrypted)Plsql programs(encrypted)
Plsql programs(encrypted)
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
plsql Lec11
plsql Lec11 plsql Lec11
plsql Lec11
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
 
Practice create procedure
Practice   create procedurePractice   create procedure
Practice create procedure
 
plsql les10
 plsql les10 plsql les10
plsql les10
 
Mc amca04919 plsql programs
Mc amca04919 plsql programsMc amca04919 plsql programs
Mc amca04919 plsql programs
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
 
plsql Les05
plsql Les05 plsql Les05
plsql Les05
 
Sql Queries
Sql QueriesSql Queries
Sql Queries
 
Tables
TablesTables
Tables
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
 
Sql 99 and_some_techniques
Sql 99 and_some_techniquesSql 99 and_some_techniques
Sql 99 and_some_techniques
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Context Level DFD
Context Level DFDContext Level DFD
Context Level DFD
 
Plsqlobj
PlsqlobjPlsqlobj
Plsqlobj
 
Pl sql student guide v 3
Pl sql student guide v 3Pl sql student guide v 3
Pl sql student guide v 3
 
Sqlii
SqliiSqlii
Sqlii
 
C++ syntax summary
C++ syntax summaryC++ syntax summary
C++ syntax summary
 

Similar to Plsql task answers

MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
gilpinleeanna
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
jhe04
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
Achmad Solichin
 

Similar to Plsql task answers (20)

MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
 
Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03
 
Dump Answers
Dump AnswersDump Answers
Dump Answers
 
Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Oracle
OracleOracle
Oracle
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
SQl
SQlSQl
SQl
 
Function in PL/SQL
Function in PL/SQLFunction in PL/SQL
Function in PL/SQL
 
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole CollegeDivyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
 
February0504 pm
February0504 pmFebruary0504 pm
February0504 pm
 
Apurv Gupta, BCA ,Final year , Dezyne E'cole College
 Apurv Gupta, BCA ,Final year , Dezyne E'cole College Apurv Gupta, BCA ,Final year , Dezyne E'cole College
Apurv Gupta, BCA ,Final year , Dezyne E'cole College
 
Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Write a C++ program with a function defined to give the person a .pdf
Write a C++ program with a function defined to give the person a .pdfWrite a C++ program with a function defined to give the person a .pdf
Write a C++ program with a function defined to give the person a .pdf
 
Les02
Les02Les02
Les02
 
PL_PKG_TASK
PL_PKG_TASKPL_PKG_TASK
PL_PKG_TASK
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Plsql task answers

  • 1. PLSQL: 1) Write a PL/SQL block to accept a year input and check whether it is a leap year. DECLARE v_YEAR NUMBER(4) := &P_YEAR; v_REMAINDER1 NUMBER(5,2); v_REMAINDER2 NUMBER(5,2); v_REMAINDER3 NUMBER(5,2); BEGIN v_REMAINDER1 := MOD(v_YEAR,4); v_REMAINDER2 := MOD(v_YEAR,100); v_REMAINDER3 := MOD(v_YEAR,400); IF ((v_REMAINDER1 = 0 AND v_REMAINDER2 <> 0 ) OR v_REMAINDER3 = 0) THEN DBMS_OUTPUT.PUT_LINE(v_YEAR || ' is a leap year'); ELSE DBMS_OUTPUT.PUT_LINE(v_YEAR || ' is not a leap year'); END IF; END; 2) Write a PL/SQL block which will accept the employee number and print the annual_salary as well as the bonus. The PL/SQL block should: Calculate the annual salary as salary * 12 Calculate the bonus as indicated in the following table: Annual Salary Bonus >= 20,000 2000 19,999–10,000 1000 <= 9,999 500 DECLARE V_EMP_ID NUMBER := &EMPLOYEE_ID; V_SAL NUMBER(7,2); V_BONUS NUMBER(7,2); V_ANN_SALARY NUMBER(15,2); BEGIN SELECT SALARY INTO V_SAL FROM EMPLOYEES WHERE EMPLOYEE_ID = V_EMP_ID; V_ANN_SALARY := V_SAL * 12; DBMS_OUTPUT.PUT_LINE('Annual Salary is : '||V_ANN_SALARY); IF V_ANN_SALARY >= 20000 THEN
  • 2. V_BONUS := 2000; ELSIF V_ANN_SALARY <= 19999 AND V_ANN_SALARY >=10000 THEN V_BONUS := 1000; ELSE V_BONUS := 500; END IF; DBMS_OUTPUT.PUT_LINE ('The Bonus is $ ' || TO_CHAR(V_BONUS)); END; 3) Declare a cursor named EMP_CUR to select the employee’s last name, salary, and hire date from the EMPLOYEES table Process each row from the cursor, and if the salary is greater than 15,000 and the hire date is later than 01-FEB-1988, display the employee name, salary, and hire date in the format shown in the following sample output: DECLARE CURSOR C_EMP_CUR IS SELECT last_name,salary,hire_date FROM EMPLOYEES; V_ENAME VARCHAR2(25); v_SAL NUMBER(7,2); V_HIREDATE DATE; BEGIN OPEN C_EMP_CUR; FETCH C_EMP_CUR INTO V_ENAME,V_SAL,V_HIREDATE; WHILE C_EMP_CUR%FOUND LOOP IF V_SAL > 15000 AND V_HIREDATE >= TO_DATE('01-FEB-1988','DD-MON-YYYY') THEN DBMS_OUTPUT.PUT_LINE (V_ENAME || ' earns ' || TO_CHAR(V_SAL)|| ' and joined the organization on ' || TO_DATE(V_HIREDATE,'DD-Mon-YYYY')); END IF; FETCH C_EMP_CUR INTO V_ENAME,V_SAL,V_HIREDATE; END LOOP; CLOSE C_EMP_CUR; END;
  • 3. 4) Create a PL/SQL block to retrieve and output the last name and department ID of each employee from the EMPLOYEES table for those employees whose EMPLOYEE_ID is less than 115. In the PL/SQL block, use a cursor FOR loop strategy instead of the OPEN / FETCH /CLOSE cursor methods used in the previous practice. 1. In the declarative section: • Create two associative arrays. The unique key column for both arrays should be of the BINARY INTEGER data type. One array holds the employee’s last name and the other holds the department ID. • Declare a counter variable to be used in the executable section • Declare a cursor that selects the last name and department ID for employees whose ID is less than 115 DECLARE TYPE Table_Ename IS table of employees.last_name%TYPE INDEX BY BINARY_INTEGER; TYPE Table_dept IS table of employees.department_id%TYPE INDEX BY BINARY_INTEGER; Tename Table_Ename; Tdept Table_dept; i BINARY_INTEGER :=0; CURSOR Namedept IS SELECT last_name,department_id FROM employees WHERE employee_id < 115; BEGIN FOR emprec in Namedept LOOP i := i +1; Tename(i) := emprec.last_name; Tdept(i) := emprec.department_id; DBMS_OUTPUT.PUT_LINE ('Employee: ' || Tename(i) || ' is in department number: ' || Tdept(i)); END LOOP; END; 5) Create a table: CREATE TABLE analysis (ename Varchar2(20), years Number(2), sal Number(8,2) ); Write a PL/SQL block that handles an exception, as follows: 1. Declare variables for the employee last name, salary, and hire date. Use a substitution variable for the employee last name. Then, query the employees table for the last_name, salary, and hire_date of the specified employee. 2. If the employee has been with the organization for more than five years, and if that employee’s salary is less than 3,500, raise an exception. In the exception handler, perform the following: • Output the following information: employee last name and the message “due for a raise,” similar to the following:
  • 4. Insert the last name, years of service, and salary into the analysis table. 3. If there is no exception, output the employee last name and the message “not due for a raise,” similar to the following: Verify the results by querying the analysis table. Use the following test cases to test the PL/SQL block. LAST_NAME MESSAGE Austin Not due for a raise Nayer Due for a raise Fripp Not due for a raise Khoo Due for a raise SET SERVEROUTPUT ON; DECLARE E_DUE_FOR_RAISE EXCEPTION; V_HIREDATE EMPLOYEES.HIRE_DATE%TYPE; V_ENAME EMPLOYEES.LAST_NAME%TYPE := INITCAP( '& B_ENAME'); V_SAL EMPLOYEES.SALARY%TYPE; V_YEARS NUMBER(2); BEGIN SELECT LAST_NAME,SALARY,HIRE_DATE INTO V_ENAME,V_SAL,V_HIREDATE FROM employees WHERE last_name = V_ENAME; V_YEARS := MONTHS_BETWEEN(SYSDATE,V_HIREDATE)/12; IF V_SAL < 3500 AND V_YEARS > 5 THEN RAISE E_DUE_FOR_RAISE; ELSE DBMS_OUTPUT.PUT_LINE (' not due for a raise'); END IF; EXCEPTION WHEN E_DUE_FOR_RAISE THEN BEGIN DBMS_OUTPUT.PUT_LINE (V_NAME || ' due for a raise'); INSERT INTO ANALYSIS(ENAME,YEARS,SAL) VALUES (V_ENAME,V_YEARS,V_SAL); END; END; /
  • 5. SELECT * FROM analysis; 6) Create, compile, and invoke the ADD_JOB procedure and review the results. a) Create a procedure called ADD_JOB to insert a new job into the JOBS table. Provide the ID and job title using two parameters. Note: You can create the procedure (and other objects) by entering the code in the SQL Worksheet area, and then click the Run Script (F5) icon. This creates and compiles the procedure. To find out whether or not the procedure has any errors, click the procedure name in the procedure node, and then select Compile from the pop-up menu. b) Invoke the procedure with IT_DBA as the job ID and Database Administrator as the job title. Query the JOBS table and view the results. c) Invoke your procedure again, passing a job ID of ST_MAN and a job title of Stock Manager. What happens and why? a) CREATE OR REPLACE PROCEDURE add_job( p_jobid jobs.job_id%type, p_jobtitle jobs.job_title%type) IS BEGIN INSERT INTO job(job_id, job_title) VALUES(p_jobid, p_jobtitle); COMMIT; END add_job; / b) EXECUTE add_job('IT_DBA', 'Database Administrator'); SELECT * FROM jobs; c) An exception occurs because there is a Unique key integrity constraint on the JOB_ID column. 7) 7a. Create a procedure called UPD_JOB to update the job title. Provide the job ID and a new title using two parameters. Include the necessary exception handling if no update occurs. CREATE OR REPLACE PROCEDURE upd_job( p_jobid jobs.job_id%type, p_jobtitle jobs.job_title%type) IS BEGIN UPDATE job SET job_title = p_jobtitle WHERE job_id = p_jobid; IF sql%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20000, 'No job updated'); ELSE COMMIT;
  • 6. END IF; END upd_job; / 7b) Invoke the procedure to change the job title of the job ID IT_DBA to Data Administrator. Query the JOBS table and view the results. EXECUTE add_job('IT_DBA', 'Data Administrator'); SELECT * FROM jobs; 7c) Test the exception-handling section of the procedure by trying to update a job that does not exist. You can use the job ID IT_WEB and the job title Web Master. EXECUTE upd_job('IT_WEB', 'Web Master'); SELECT * FROM jobs where job_id = 'IT_WEB'; 8) Create a procedure called GET_EMPLOYEE to query the EMPLOYEES table, retrieving the salary and job ID for an employee when provided with the employee ID. a) Create a procedure that returns a value from the SALARY and JOB_ID columns for a specified employee ID. Remove syntax errors, if any, and then recompile the code. 9) Create and invoke the GET_JOB function to return a job title. 9a) Create and compile a function called GET_JOB to return a job title. CREATE OR REPLACE FUNCTION get_job (p_jobid IN jobs.job_id%type) RETURN jobs.job_title%type IS v_title jobs.job_title%type; BEGIN SELECT job_title INTO v_title FROM jobs WHERE job_id = p_jobid; RETURN v_title; END get_job; / 9b)Create a VARCHAR2 host variable called b_title, allowing a length of 35 characters. Invoke the function with job ID SA_REP to return the value in the host variable, and then print the host variable to view the result. VARIABLE b_title VARCHAR2(35) EXECUTE :b_title := get_job ('SA_REP'); PRINT b_title
  • 7. 10) Create a function called GET_ANNUAL_COMP to return the annual salary computed from an employee’s monthly salary and commission passed as parameters. 10 a) Create the GET_ANNUAL_COMP function, which accepts parameter values for the monthly salary and commission. Either or both values passed can be NULL, but the function should still return a non-NULL annual salary. Use the following basic formula to calculate the annual salary: (salary*12) + (commission_pct*salary*12) CREATE OR REPLACE FUNCTION get_annual_comp( p_sal IN employees.salary%TYPE, p_comm IN employees.commission_pct%TYPE) RETURN NUMBER IS BEGIN RETURN (NVL(p_sal,0) * 12 + (NVL(p_comm,0) * nvl(p_sal,0) * 12)); END get_annual_comp; / 10b) Use the function in a SELECT statement against the EMPLOYEES table for employees in department 30. SELECT employee_id, last_name, get_annual_comp(salary,commission_pct) "Annual Compensation" FROM employees WHERE department_id=30 / 11) Create a procedure, ADD_EMPLOYEE, to insert a new employee into the EMPLOYEES table. The procedure should call a VALID_DEPTID function to check whether the department ID specified for the new employee exists in the DEPARTMENTS table. 11a) Create a function called VALID_DEPTID to validate a specified department ID and return a BOOLEAN value of TRUE if the department exists. CREATE OR REPLACE FUNCTION valid_deptid( p_deptid IN departments.department_id%TYPE) RETURN BOOLEAN IS v_dummy PLS_INTEGER; BEGIN SELECT 1 INTO v_dummy FROM departments WHERE department_id = p_deptid; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END valid_deptid;
  • 8. 11b) Create the ADD_EMPLOYEE procedure to add an employee to the EMPLOYEES table. The row should be added to the EMPLOYEES table if the VALID_DEPTID function returns TRUE; otherwise, alert the user with an appropriate message. Provide the following parameters: - first_name - last_name - email - job: Use 'SA_REP' as the default. - mgr: Use 145 as the default. - sal: Use 1000 as the default. - comm: Use 0 as the default. - deptid: Use 30 as the default. - Use the EMPLOYEES_SEQ sequence to set the employee_id column. − Set the hire_date column to TRUNC(SYSDATE). CREATE OR REPLACE PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30) IS BEGIN IF valid_deptid(p_deptid) THEN INSERT INTO employees(employee_id, first_name, last_name, email,job_id, manager_id, hire_date, salary, commission_pct, department_id) VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name, p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm, p_deptid); ELSE RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try again.'); END IF; END add_employee; 11c) Call ADD_EMPLOYEE for the name 'Jane Harris' in department 15, leaving other parameters with their default values. What is the result? EXECUTE add_employee('Jane', 'Harris', 'JAHARRIS', p_deptid=> 15); 11d) Add another employee named Joe Harris in department 80, leaving the remaining parameters with their default values. What is the result? EXECUTE add_employee('Joe', 'Harris', 'JAHARRIS', p_deptid=> 80)
  • 9. 12) 1) Create a package specification and body called JOB_PKG, containing a copy of your ADD_JOB, UPD_JOB, and DEL_JOB procedures as well as your GET_JOB function. Note: Use the code from your previously saved procedures and functions when creating the package. You can copy the code in a procedure or function, and then paste the code into the appropriate section of the package. a) Create the package specification including the procedures and function headings as public constructs. CREATE OR REPLACE PACKAGE job_pkg IS PROCEDURE add_job (p_jobid jobs.job_id%TYPE, p_jobtitle jobs.job_title%TYPE); PROCEDURE del_job (p_jobid jobs.job_id%TYPE); FUNCTION get_job (p_jobid IN jobs.job_id%type) RETURN jobs.job_title%type; PROCEDURE upd_job(p_jobid IN jobs.job_id%TYPE, p_jobtitle IN jobs.job_title%TYPE); END job_pkg; / SHOW ERRORS b) Create the package body with the implementations for each of the subprograms. CREATE OR REPLACE PACKAGE BODY job_pkg IS PROCEDURE add_job ( p_jobid jobs.job_id%TYPE, p_jobtitle jobs.job_title%TYPE) IS BEGININSERT INTO jobs (job_id, job_title) VALUES (p_jobid, p_jobtitle); COMMIT; END add_job; PROCEDURE del_job (p_jobid jobs.job_id%TYPE) IS BEGIN DELETE FROM jobs WHERE job_id = p_jobid; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20203, 'No jobs deleted.'); END IF; END DEL_JOB; FUNCTION get_job (p_jobid IN jobs.job_id%type) RETURN jobs.job_title%type IS v_title jobs.job_title%type; BEGIN SELECT job_title INTO v_title FROM jobs WHERE job_id = p_jobid; RETURN v_title; END get_job; PROCEDURE upd_job( p_jobid IN jobs.job_id%TYPE, p_jobtitle IN jobs.job_title%TYPE) IS BEGIN
  • 10. UPDATE jobs SET job_title = p_jobtitle WHERE job_id = p_jobid; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'No job updated.'); END IF; END upd_job; END job_pkg; / c) Invoke your ADD_JOB package procedure by passing the values IT_SYSAN and SYSTEMS ANALYST as parameters. EXECUTE job_pkg.add_job('IT_SYSAN', 'Systems Analyst'); 13) Create and invoke a package that contains private and public constructs. a) Create a package specification and a package body called EMP_PKG that contains the following procedures and function that you created earlier: i) ADD_EMPLOYEE procedure as a public construct ii) GET_EMPLOYEE procedure as a public construct iii) VALID_DEPTID function as a private construct CREATE OR REPLACE PACKAGE emp_pkg IS PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30); PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE); END emp_pkg; / CREATE OR REPLACE PACKAGE BODY emp_pkg IS FUNCTION valid_deptid(p_deptid IN departments.department_id%TYPE) RETURN BOOLEAN IS v_dummy PLS_INTEGER; BEGIN SELECT 1 INTO v_dummy FROM departments WHERE department_id = p_deptid; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE;
  • 11. END valid_deptid; PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30) IS BEGIN IF valid_deptid(p_deptid) THEN INSERT INTO employees(employee_id, first_name, last_name, email, job_id, manager_id, hire_date, salary, commission_pct, department_id) VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name, p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm, p_deptid); ELSE RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try again.'); END IF; END add_employee; PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE) IS BEGIN SELECT salary, job_id INTO p_sal, p_job FROM employees WHERE employee_id = p_empid; END get_employee; END emp_pkg; / b) Invoke the EMP_PKG.ADD_EMPLOYEE procedure, using department ID 15 for employee Jane Harris with the email ID JAHARRIS. Because department ID 15 does not exist, you should get an error message as specified in the exception handler of your procedure. EXECUTE emp_pkg.add_employee('Jane', 'Harris','JAHARRIS', p_deptid => 15); c) Invoke the ADD_EMPLOYEE package procedure by using department ID 80 for employee David Smith with the email ID DASMITH. EXECUTE emp_pkg.add_employee('David', 'Smith','DASMITH', p_deptid => 80); 14)
  • 12. modify the code for the EMP_PKG package that you created earlier, and then overload the ADD_EMPLOYEE procedure. Next, you create two overloaded functions called GET_EMPLOYEE in the EMP_PKG package. You also add a public procedure to EMP_PKG to populate a private PL/SQL table of valid department IDs and modify the VALID_DEPTID function to use the private PL/SQL table contents to validate department ID values. You also change the VALID_DEPTID validation processing function to use the private PL/SQL table of department IDs. Finally, you reorganize the subprograms in the package specification and the body so that they are in alphabetical sequence. 1) Modify the code for the EMP_PKG package that you created in Practice 4 step 2, and overload the ADD_EMPLOYEE procedure. a) In the package specification, add a new procedure called ADD_EMPLOYEE that accepts the following three parameters: i) First name ii) Last name iii) Department ID CREATE OR REPLACE PACKAGE emp_pkg IS PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30); /* New overloaded add_employee */ PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_deptid employees.department_id%TYPE); PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE); END emp_pkg; b) Implement the new ADD_EMPLOYEE procedure in the package body as follows: i) Format the email address in uppercase characters, using the first letter of the first name concatenated with the first seven letters of the last name. ii) The procedure should call the existing ADD_EMPLOYEE procedure to perform the actual INSERT operation using its parameters and formatted email to supply the values. iii) Click Run Script to create the package. Compile the package. CREATE OR REPLACE PACKAGE BODY emp_pkg IS FUNCTION valid_deptid(p_deptid IN departments.department_id%TYPE) RETURN BOOLEAN IS v_dummy PLS_INTEGER;
  • 13. BEGIN SELECT 1 INTO v_dummy FROM departments WHERE department_id = p_deptid; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END valid_deptid; PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE,p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30) IS BEGIN IF valid_deptid(p_deptid) THEN INSERT INTO employees(employee_id, first_name, last_name, email, job_id, manager_id, hire_date, salary, commission_pct, department_id) VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name, p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm, p_deptid); ELSE RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try again.'); END IF; END add_employee; /* New overloaded add_employee procedure */ PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_deptid employees.department_id%TYPE) IS p_email employees.email%type; BEGIN p_email := UPPER(SUBSTR(p_first_name, 1, 1)||SUBSTR(p_last_name, 1, 7)); add_employee(p_first_name, p_last_name, p_email, p_deptid => p_deptid); END; /* End declaration of the overloaded add_employee procedure */ PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE) IS BEGIN SELECT salary, job_id INTO p_sal, p_job FROM employees WHERE employee_id = p_empid; END get_employee;
  • 14. END emp_pkg; / c) Invoke the new ADD_EMPLOYEE procedure using the name Samuel Joplin to be added to department 30. EXECUTE emp_pkg.add_employee('Samuel', 'Joplin', 30); 15) In the EMP_PKG package, create two overloaded functions called GET_EMPLOYEE: 15a) In the package specification, add the following functions: i) The GET_EMPLOYEE function that accepts the parameter called p_emp_id based on the employees.employee_id%TYPE type. This function should return EMPLOYEES%ROWTYPE. ii) The GET_EMPLOYEE function that accepts the parameter called p_family_name of type employees.last_name%TYPE. This function should return EMPLOYEES%ROWTYPE. CREATE OR REPLACE PACKAGE emp_pkg IS PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30); PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_deptid employees.department_id%TYPE); PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE); /* New overloaded get_employees functions specs starts here: */ FUNCTION get_employee(p_emp_id employees.employee_id%type) return employees%rowtype; FUNCTION get_employee(p_family_name employees.last_name%type) return employees%rowtype; /* New overloaded get_employees functions specs ends here. */ END emp_pkg; 15 b) In the package body: i) Implement the first GET_EMPLOYEE function to query an employee using the employee’s ID. ii) Implement the second GET_EMPLOYEE function to use the equality operator on the value supplied in the p_family_name parameter
  • 15. CREATE OR REPLACE PACKAGE emp_pkg IS PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30); PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_deptid employees.department_id%TYPE); PROCEDURE get_employee(p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE); /* New overloaded get_employees functions specs starts here: */ FUNCTION get_employee(p_emp_id employees.employee_id%type) return employees%rowtype; FUNCTION get_employee(p_family_name employees.last_name%type) return employees%rowtype; /* New overloaded get_employees functions specs ends here. */ END emp_pkg; -- package body CREATE OR REPLACE PACKAGE BODY emp_pkg IS FUNCTION valid_deptid(p_deptid IN departments.department_id%TYPE) RETURN BOOLEAN IS v_dummy PLS_INTEGER; BEGIN SELECT 1 INTO v_dummy FROM departments WHERE department_id = p_deptid; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END valid_deptid; PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_email employees.email%TYPE, p_job employees.job_id%TYPE DEFAULT 'SA_REP', p_mgr employees.manager_id%TYPE DEFAULT 145, p_sal employees.salary%TYPE DEFAULT 1000, p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid employees.department_id%TYPE DEFAULT 30) IS BEGIN IF valid_deptid(p_deptid) THEN INSERT INTO employees(employee_id, first_name, last_name, email, job_id, manager_id, hire_date, salary,
  • 16. commission_pct, department_id) VALUES (employees_seq.NEXTVAL, p_first_name, p_last_name, p_email, p_job, p_mgr, TRUNC(SYSDATE), p_sal, p_comm, p_deptid); ELSE RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try again.'); END IF; END add_employee; PROCEDURE add_employee( p_first_name employees.first_name%TYPE, p_last_name employees.last_name%TYPE, p_deptid employees.department_id%TYPE) IS p_email employees.email%type; BEGIN p_email := UPPER(SUBSTR(p_first_name, 1, 1)||SUBSTR(p_last_name, 1, 7)); add_employee(p_first_name, p_last_name, p_email, p_deptid => p_deptid); END; PROCEDURE get_employee( p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE) IS BEGIN SELECT salary, job_id INTO p_sal, p_job FROM employees WHERE employee_id = p_empid; END get_employee; /* New get_employee function declaration starts here */ FUNCTION get_employee(p_emp_id employees.employee_id%type) return employees%rowtype IS rec_emp employees%rowtype; BEGIN SELECT * INTO rec_emp FROM employees WHERE employee_id = p_emp_id; RETURN rec_emp; END; FUNCTION get_employee(p_family_name employees.last_name%type) return employees%rowtype IS rec_emp employees%rowtype; BEGIN SELECT * INTO rec_emp FROM employees WHERE last_name = p_family_name; RETURN rec_emp; END; /* New overloaded get_employee function declaration ends here */ END emp_pkg; 16) Example for utl_file package:
  • 17. CREATE OR REPLACE PROCEDURE employee_report( p_dir IN VARCHAR2, p_filename IN VARCHAR2) IS f UTL_FILE.FILE_TYPE; CURSOR cur_avg IS SELECT last_name, department_id, salary FROM employees outer WHERE salary > (SELECT AVG(salary) FROM employees inner GROUP BY outer.department_id) ORDER BY department_id; BEGIN f := UTL_FILE.FOPEN(p_dir, p_filename,'W'); UTL_FILE.PUT_LINE(f, 'Employees who earn more than average salary: '); UTL_FILE.PUT_LINE(f, 'REPORT GENERATED ON ' ||SYSDATE); UTL_FILE.NEW_LINE(f); FOR emp IN cur_avg LOOP UTL_FILE.PUT_LINE(f, RPAD(emp.last_name, 30) || ' ' || LPAD(NVL(TO_CHAR(emp.department_id,'9999'),'-'), 5) || ' ' || LPAD(TO_CHAR(emp.salary, '$99,999.00'), 12)); END LOOP; UTL_FILE.NEW_LINE(f); UTL_FILE.PUT_LINE(f, '*** END OF REPORT ***'); UTL_FILE.FCLOSE(f); END employee_report;