You are on page 1of 2

Lab Session 4 - Solution

Regulations
 Attendance is mandatory
 Every student should have his own laptop on which:
o Oracle XE and SQL Developer are mounted and working correctly
o A user account is created and has a copy of HR schema
 Each PL/SQL LAB Session is followed by a 15 mn quiz on paper; the grade of the quiz will
be part of the lab final grade.

COUNTRIES (country_id, country_name, region_id)


DEPARTMENTS (department_id, department_name, manager_id, location_id)
EMPLOYEES (employee_id, first_name, last_name, email, phone_number,
hire_date, job_id, salary, commission_pct, manager_id,
department_id)
JOB (job_id, title, min_salary, max_salary)
JOB_HISTORY (employee_id, start_date, end_date, job_id, department_id)
LOCATIONS (location_id, street_address, postal_code, city, state_province,
country_id)
REGIONS (region_id, region_name)

1. Write a trigger to ensure no changes can be made to EMPLOYEES table before


6am and after 10pm in a day.
create or replace trigger nochange
before delete or insert or update ON employees
for each row
BEGIN
IF TO_CHAR(SYSDATE,'HH24') <6 or TO_CHAR(SYSDATE,'HH24')>22
THEN
RAISE_APPLICATION_ERROR(-20000, 'Invalid hour!')1;
END IF;
END;
2. Write a trigger check_comm to limit the commission to the employees working as
SA_REP or SA_MAN and ensure that an employee earning a salary = max_salary
of his job should not have commission_pct > 2%.
create or replace trigger check_comm
before insert or update
of commission_pct,salary,job_id on employees
for each row
declare
v_max_sal JOBS.MAX_SALARY%TYPE;

1
Non Oracle Error numbers are defined between -20,000 and -20,999.
BEGIN

select max_salary into v_max_sal from jobs where job_id =


:NEW.job_id;
IF :new.salary>=v_max_sal and :new.commission_pct > 0.02 THEN
RAISE_APPLICATION_ERROR(-20000,'Max salary already
Reached!');
END IF;
END;

3. Write a trigger to write the following details into job history: Employee ID, old job
ID, old department ID, hire date of the employee for start date, system date for end
date, whenever the job is changed for an employee. But if a row is already present
for employee job history then the start date should be the end date of that row +1.
create or replace trigger job_log_change
after update of job_id
on employees
for each row
declare
v_enddate DATE;
v_startdate DATE;
BEGIN
SELECT max(end_date) into v_enddate FROM job_history WHERE
employee_id = :old.employee_id;
IF v_enddate IS NULL THEN
v_startdate := :old.hire_date;
ELSE
v_startdate := v_enddate + 1;
END IF;
insert into job_history values (:old.employee_id, v_startdate,
sysdate, :old.job_id, :old.department_id);
END;

To test the trigger when job_history.enddate is NULL, we have to modify the not null constraint
(click on job_history then edit/properties).

You might also like