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

SQL practice questions set - 2
SQL practice questions set - 2SQL practice questions set - 2
SQL practice questions set - 2Mohd Tousif
 
Pl sql student guide v 4
Pl sql student guide v 4Pl sql student guide v 4
Pl sql student guide v 4Nexus
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with outputNexus
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sqlCharan Reddy
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseSalman Memon
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankMd Mudassir
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3Mohd Tousif
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQLEDB
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
Les07 (using the set operators)
Les07 (using the set operators)Les07 (using the set operators)
Les07 (using the set operators)Achmad Solichin
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseSalman Memon
 

What's hot (20)

SQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftjSQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftj
 
SQL practice questions set - 2
SQL practice questions set - 2SQL practice questions set - 2
SQL practice questions set - 2
 
Pl sql student guide v 4
Pl sql student guide v 4Pl sql student guide v 4
Pl sql student guide v 4
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with output
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data Base
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question Bank
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Sql queires
Sql queiresSql queires
Sql queires
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
Q on subquery
Q on subqueryQ on subquery
Q on subquery
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
1 z0 047
1 z0 0471 z0 047
1 z0 047
 
Les07 (using the set operators)
Les07 (using the set operators)Les07 (using the set operators)
Les07 (using the set operators)
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 
Sql functions
Sql functionsSql functions
Sql functions
 

Viewers also liked

Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answersvijaybusu
 
Practice create procedure
Practice   create procedurePractice   create procedure
Practice create procedurecit gubbi
 
Mc amca04919 plsql programs
Mc amca04919 plsql programsMc amca04919 plsql programs
Mc amca04919 plsql programsAshwin Kumar
 
Sql task answers
Sql task answersSql task answers
Sql task answersNawaz Sk
 
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-solutionsAshwin Kumar
 
Sql Queries
Sql QueriesSql Queries
Sql Querieswebicon
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库renguzi
 
Sql 99 and_some_techniques
Sql 99 and_some_techniquesSql 99 and_some_techniques
Sql 99 and_some_techniquesAlexey Kiselyov
 
Pl sql student guide v 3
Pl sql student guide v 3Pl sql student guide v 3
Pl sql student guide v 3Nexus
 

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
 
Sql task answers
Sql task answersSql task answers
Sql task answers
 
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
 

Similar to Plsql task answers

Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Thuan Nguyen
 
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.docxgilpinleeanna
 
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 03Thuan Nguyen
 
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 10Thuan Nguyen
 
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 01Thuan Nguyen
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxmetriohanzel
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handoutsjhe04
 
Function in PL/SQL
Function in PL/SQLFunction in PL/SQL
Function in PL/SQLPooja Dixit
 
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 Collegedezyneecole
 
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 Collegedezyneecole
 
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 07Thuan Nguyen
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Achmad Solichin
 
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 .pdfarihantgiftgallery
 

Similar to Plsql task answers (20)

Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
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
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

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;