Sei sulla pagina 1di 20

1.2. Create a function called GET_ANNUAL_COMP to return the annual salary comput ed 2.

from an employee s monthly salary and commission passed as parameters. 3. 4.a. Develop and store the GET_ANNUAL_COMP function, accepting parameter 5.values for monthly salary and commission. Either or both values passed can be 6.NULL, but the function should still return a non-NULL annual salary. Use the 7.following basic formula to calculate the annual salary: 8.(salary*12) + (commission_pct*salary*12) 9. 10.CREATE OR REPLACE FUNCTION get_annual_comp( 11.sal IN employees.salary%TYPE, 12.comm IN employees.commission_pct%TYPE) 13.RETURN NUMBER IS 14.BEGIN 15.RETURN (NVL(sal,0) * 12 + (NVL(comm,0) * nvl(sal,0) * 12)); 16.END get_annual_comp; 17./ 18.Function created. 19. 20.NVL = nvl check the variable of the salary if it is null then zero is use if the value is not null then the value of salary is used 21. 22.b. Use the function in a SELECT statement against the EMPLOYEES table for 23.employees in department 30. 24.SELECT employee_id, last_name, 25.get_annual_comp(salary,commission_pct) "Annual Compensation" 26.FROM employees 27.WHERE department_id=30 28./ 29. 30.3. Create a procedure, ADD_EMPLOYEE, to insert a new employee into the EMPLOY EES 31.table. The procedure should call a VALID_DEPTID function to check whether the 32.department ID specified for the new employee exists in the DEPARTMENTS table. 33. 34.a. Create a function VALID_DEPTID to validate a specified department ID and 35.return a BOOLEAN value of TRUE if the department exists. 36. 37.CREATE OR REPLACE FUNCTION valid_deptid( 38.deptid IN departments.department_id%TYPE) 39.RETURN BOOLEAN IS 40.dummy PLS_INTEGER; 41.BEGIN 42.SELECT 1 43.INTO dummy 44.FROM departments 45.WHERE department_id = deptid; 46.RETURN TRUE; 47.EXCEPTION 48.WHEN NO_DATA_FOUND THEN 49.RETURN FALSE; 50.END valid_deptid; 51./ 52.Function created. 53. 54.b. Create the ADD_EMPLOYEE procedure to add an employee to the EMPLOYEES 55.table. The row should be added to the EMPLOYEES table if the VALID_DEPTID 56.function returns TRUE; otherwise, alert the user with an appropriate message. 57.Provide the following parameters (with defaults specified in parentheses):

58.first_name, last_name, email, job (SA_REP), mgr (145), sal (1000), 59.comm (0), and deptid (30). Use the EMPLOYEES_SEQ sequence to set the 60.employee_id column, and set hire_date to TRUNC(SYSDATE). 61. 62.CREATE OR REPLACE PROCEDURE add_employee( 63.first_name employees.first_name%TYPE, 64.last_name employees.last_name%TYPE, 65.email employees.email%TYPE, 66.job employees.job_id%TYPE DEFAULT 'SA_REP', 67.mgr employees.manager_id%TYPE DEFAULT 145, 68.sal employees.salary%TYPE DEFAULT 1000, 69.comm employees.commission_pct%TYPE DEFAULT 0, 70.deptid employees.department_id%TYPE DEFAULT 30) IS 71.BEGIN 72.IF valid_deptid(deptid) THEN 73.INSERT INTO employees(employee_id, first_name, last_name, email, 74.job_id, manager_id, hire_date, salary, commission_pct, 75.department_id) 76.VALUES (employees_seq.NEXTVAL, first_name, last_name, email, 77.job, mgr, TRUNC(SYSDATE), sal, comm, deptid); 78.ELSE 79.RAISE_APPLICATION_ERROR (-20204, 'Invalid department ID. Try again.'); 80.END IF; 81.END add_employee; 82./ 83.Procedure created. 84. 85.c. Call ADD_EMPLOYEE for the name Jane Harris in department 15, leaving 86.other parameters with their default values. What is the result? 87. 88.Note: If the database server time is not between 8:00 and 18:00, the Secure_e mployees 89.trigger will be fired on performing any DML operation on the EMPLOYEES table. Disable 90.the aforesaid trigger to overcome this problem. 91. 92.EXECUTE add_employee('Jane', 'Harris', 'JAHARRIS', deptid=> 15) 93.BEGIN add_employee('Jane', 'Harris', 'JAHARRIS', deptid=> 15); END; 94.* 95.ERROR at line 1: 96.ORA-20204: Invalid department ID. Try again. 97.ORA-06512: at "ORA1.ADD_EMPLOYEE", line 17 98.ORA-06512: at line 1 99. 100.d. Add another employee named Joe Harris in department 80, leaving 101.remaining parameters with their default values. What is the result? 102.EXECUTE add_employee('Joe', 'Harris', 'JAHARRIS', deptid=> 80) 103.PL/SQL procedure successfully completed. __________________ //SQL CURSOR Attributes for Implicit Cursors VARIABLE rows_deleted VARCHAR2(30) DECLARE empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = empno; :rows_deleted := (SQL%ROWCOUNT || 'row deleted.');

END; / PRINT rows_deleted //Simple IF Statement SET SERVEROUTPUT ON DECLARE myage number := 1; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF; END; //IF THEN ELSE Statement SET SERVEROUTPUT ON DECLARE myage number := 31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; // IF ELSIF ELSE Statement SET SERVEROUTPUT ON DECLARE myage number := 31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' ELSE DBMS_OUTPUT.PUT_LINE(' END IF; END; // NULL Vlaues in IF Statements SET SERVEROUTPUT ON DECLARE myage number; BEGIN IF myage < 11 THEN

I am a child '); I am young '); I am in my twenties '); I am in my thirties '); I am always young ');

DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; // CASE Expressions SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'VERY GOOD' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE('Grade: '|| grade || ' Appraisal ' || appraisal); END; / // Searched CASE Expressions SET SERVEROUTPUT ON DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal:= CASE WHEN grade = 'A' THEN 'EXCELLENT' WHEN grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE('Grade: '|| grade || ' Appraisal ' || appraisal); END; //CASE Statement SET SERVEROUTPUT ON DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 205; BEGIN CASE mngid WHEN 205 THEN SELECT department_id, department_name INTO deptid, deptname FROM departments WHERE manager_id = 205; SELECT count(*) INTO emps FROM employees WHERE department_id = deptid; WHEN 200 THEN SELECT department_id INTO deptid from employees WHERE department_id =20; END CASE ;

DBMS_OUTPUT.PUT_LINE(' You are working in the ' || deptname || ' department. The re are ' || emps || 'employees in this department'); END; / //Basic Loops DECLARE countryId locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; counter NUMBER(2) := 1; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; LOOP INSERT INTO locations(location_id, city, country_id) VALUES ((loc_id + counter), new_city, countryid); counter := counter + 1; EXIT WHEN counter > 3; END LOOP; END; //WHILE Loops DECLARE countryId locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; counter NUMBER := 1; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; WHILE counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES ((loc_id + counter), new_city, countryid); counter := counter + 1; END LOOP; END; //FOR Loops DECLARE countryId locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES ((loc_id + i), new_city, countryid); END LOOP; END; // CREATE retired_emps TABLE CREATE TABLE retired_emps (EMPNO NUMBER(4), ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, LEAVEDATE DATE,

SAL NUMBER(7,2), COMM DEPTNO NUMBER(2))

NUMBER(7,2),

// INSERT USING %ROWTYPE Attribute DEFINE employee_number = 124 DECLARE emp_rec employees%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps(empno, ename, job, mgr, hiredate, leavedate, sal, comm, deptno) VALUES (emp_rec.employee_id, emp_rec.last_name, emp_rec.job_id, emp_rec.manager_id, emp_rec.hire_date, SYSDATE, emp_rec.salary, emp_rec.commission_pct, emp_rec.department_id); END; // INSERT a Record Using %ROWTYPE DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id, hire_date, hire_date, salary, commission_pct, department_id INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps VALUES emp_rec; END; / SELECT * FROM retired_emps; //UPDATING a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM retired_emps; emp_rec.leavedate:= SYSDATE; UPDATE retired_emps SET ROW = emp_rec WHERE empno=&employee_number; END; / SELECT * FROM retired_emps; // Example of INDEX BY Table of Records Ch 6 SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):=104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP;

FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; // Nested Tables SET SERVEROUTPUT ON DECLARE TYPE location_type IS TABLE OF locations.city%TYPE; offices location_type; table_count NUMBER; BEGIN offices := location_type('Bombay', 'Tokyo', 'Singapore','Oxford'); table_count := offices.count(); FOR i in 1..table_count LOOP DBMS_OUTPUT.PUT_LINE(offices(i)); END LOOP; END; //Fetching Data from the Cursor ch7 /* program 1 DECLARE CURSOR c_emp IS SELECT id, first_name, last_name,salary,title FROM s_emp; emp_rec BEGIN OPEN c_emp; LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title); END LOOP; CLOSE c_emp; END; / /* DECLARE CURSOR c_emp IS SELECT id, first_name, last_name,salary,title program 2 */ c_emp%rowtype; */

FROM s_emp; emp_rec BEGIN OPEN c_emp; LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; IF emp_rec.title = 'Stock Clerk' THEN UPDATE s_emp set salary=salary * 1.2 WHERE id=emp_rec.id; ELSE UPDATE s_emp set salary=salary * 1.1 WHERE id=emp_rec.id; END IF; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name ,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title); END LOOP; CLOSE c_emp; END; / //Cursor FOR LOOPS DECLARE CURSOR c_emp IS SELECT * FROM s_emp; BEGIN c_emp%rowtype;

FOR emp_rec IN c_emp LOOP dbms_output.put_line(emp_rec.id||' '||emp_rec.last_name||' '||emp_rec.sal ary); END LOOP;

-- emp_rec.last_name :='xxxx'; END; / // Cursor and Records DECLARE -- emp_rec CURSOR c_emp IS SELECT * FROM s_emp; emp_rec BEGIN OPEN c_emp; LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; c_emp%rowtype; s_emp%rowtype;

-- this statement is illegal

dbms_output.put_line(emp_rec.id||' '||emp_rec.last_name||' '||emp_rec.salar y); END LOOP; dbms_output.put_line(chr(10)||'Number of rows fetched = '||c_emp%rowcount); CLOSE c_emp; END; / // Example of %ROWCOUNT and %NOTOUND DECLARE -- emp_rec CURSOR c_emp IS SELECT * FROM s_emp; emp_rec BEGIN OPEN c_emp; LOOP c_emp%rowtype; s_emp%rowtype;

FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; dbms_output.put_line(emp_rec.id||' '||emp_rec.last_name||' '||emp_rec.salar y); END LOOP; dbms_output.put_line(chr(10)||'Number of rows fetched = '||c_emp%rowcount); CLOSE c_emp; END; / // &ROWCOUNT and %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno) ||' '|| ename); END LOOP; CLOSE emp_cursor; END ; // Cursor FOR LOOP using Subqueries BEGIN FOR emp_rec IN (SELECT * ary FROM s_emp) LOOP -- last_name, sal

dbms_output.put_line(emp_rec.last_name||' '||emp_rec.salary); END LOOP; END; / //Chap 7 The FOR UPDATE Clause // You can lock the rows with the FOR UPDATE clause in the cursor query DECLARE CURSOR c_emp IS SELECT id, first_name, last_name,salary,title FROM s_emp

FOR UPDATE; emp_rec c_emp%rowtype; BEGIN OPEN c_emp; LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; IF emp_rec.salary < 2000 THEN EMP_REC.SALARY := EMP_REC.SALARY * 1.2; UPDATE s_emp set salary= emp_rec.salary WHERE current of c_emp; ELSE EMP_REC.SALARY := EMP_REC.SALARY * 1.1; UPDATE s_emp set salary=emp_rec.salary WHERE current of c_emp; END IF; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_nam e,17) ||' '||to_char(emp_rec.salary,'999,999.00')||' '||emp_rec.title); END LOOP; CLOSE c_emp; END; / // Cursors with Parameters // Parameter data types are the same as those for scalar variables, // but you do not give them sizes. DECLARE CURSOR c_emp (p_deptid s_emp.dept_id%type, p_title VARCHAR2) IS SELECT id, last_name,salary,title,dept_id FROM s_emp WHERE dept_id = p_deptid AND title = p_title; BEGIN FOR emp_rec in c_emp (41, 'Stock Clerk') LOOP dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title ||' '||emp_rec.dept_id); END LOOP; -- ************ OPEN CURSOR WITH NEW PARAMETERS *********************

// You can pass parameters to the cursor used in a cursor FOR loop FOR emp_rec in c_emp (43, 'Warehouse Manager') LOOP dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title ||' '||emp_rec.dept_id); END LOOP; END; / //Cursors with Parameters DECLARE CURSOR c_emp (p_deptid s_emp.dept_id%type, p_title VARCHAR2) IS

SELECT id, last_name,salary,title,dept_id FROM s_emp WHERE dept_id = p_deptid AND title = p_title; emp_rec BEGIN OPEN c_emp (41, 'Stock Clerk'); LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title ||' '||emp_rec.dept_id); END LOOP; CLOSE c_emp; -- ************ OPEN CURSOR WITH NEW PARAMETERS ********************* c_emp%rowtype;

OPEN c_emp (43, 'Warehouse Manager'); LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00') ||' '||emp_rec.title ||' '||emp_rec.dept_id); END LOOP; CLOSE c_emp; END; / // Cursors with Subqueries // The subquery creates a data source consisting of department numbers and //employee head count in each department (known by alias STAFF). A table alias, t2, refers to // this temporary data source in the FROM clause. When this cursor is opened, th e active set contains // the department number, department name, and total number of employees working for the department, //provided there are three or more employees working for the department.

DECLARE CURSOR c_dept IS SELECT t1.id, t1.name, t2.staff FROM s_dept t1, (SELECT dept_id, COUNT(*) AS STAFF FROM s_emp GROUP BY dept_id) t2 WHERE t1.id = t2.dept_id; -AND t2.staff >= 3; dept_rec BEGIN OPEN c_dept; LOOP FETCH c_dept INTO dept_rec; EXIT WHEN c_dept%NOTFOUND; dbms_output.put_line(dept_rec.id||' '||dept_rec.name||' '||dept_rec.staf f); END LOOP; CLOSE c_dept; END; / // The WHERE CURRENT OF Clause // The WHERE CURRENT OF clause is used in conjunction with the FOR UPDATE clause to // refer to the current row in an explicit cursor. The WHERE CURRENT OF clause i s used in the // UPDATE or DELETE statement whereas the FOR UPDATE clause is specified in the cursor declaration. DECLARE CURSOR c_emp IS SELECT id, first_name, last_name,salary,title FROM manzer.s_emp FOR UPDATE; -NOWAIT; emp_rec c_emp%rowtype; BEGIN OPEN c_emp; LOOP FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; IF emp_rec.title = 'Stock Clerk' THEN UPDATE manzer.s_emp set salary=salary * 1.2 WHERE id=emp_rec.id; -WHERE current of c_emp; ELSE UPDATE manzer.s_emp set salary=salary * 1.1 c_dept%rowtype;

-END IF; e,17)

WHERE id=emp_rec.id; WHERE current of c_emp; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_nam

||' '||to_char(emp_rec.salary,'999,999.00' )||' '||emp_rec.title); -INSERT into temp_table values(emp_rec.id,emp_rec.salary); -COMMIT; END LOOP; CLOSE c_emp; END; / // CREATE OR REPLACE PROCEDURE update_sal (p_id IN s_emp.id%TYPE) IS -- PRAGMA AUTONOMOUS_TRANSACTION; BEGIN update s_emp set salary=100 WHERE id = p_id; commit; END; / begin update s_emp set last_name='xxx' where id=3; update_sal(&id); end; / //Chap 8 Handling Exceptions DECLARE e_invalid_department EXCEPTION; BEGIN BEGIN UPDATE s_dept SET name = 'xxx' WHERE id = &p_department_number; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20000,'Invalid department number'); END IF; EXCEPTION WHEN e_invalid_department THEN DBMS_OUTPUT.PUT_LINE('Invalid department id. ***********inner block');

END; EXCEPTION WHEN e_invalid_department THEN DBMS_OUTPUT.PUT_LINE('Invalid department id. *************outer block');

END; / // Exception handling using SQL%NOTFOUND DECLARE e_invalid_department EXCEPTION; BEGIN UPDATE s_dept SET name = 'xxx' WHERE id = &p_department_number; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20000,'Invalid department number'); END IF; dbms_output.put_line('record updated'); END; / // Cursor Loop Exception Handling DECLARE error exception; CURSOR c_emp IS SELECT id, first_name, last_name,salary,title,dept_id FROM s_emp; emp_rec c_emp%rowtype; BEGIN OPEN c_emp; LOOP BEGIN FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; if emp_rec.id = 7 then raise error; end if; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00 ')||' '||emp_rec.title); EXCEPTION when error then dbms_output.put_line('Dept Id is null for employee '||emp_rec.id); END; END LOOP; CLOSE c_emp; END; / begin DECLARE error exception; v_var1 number :='a'; CURSOR c_emp IS SELECT id, first_name, last_name,salary,title,dept_id FROM s_emp; emp_rec c_emp%rowtype; BEGIN OPEN c_emp; LOOP

BEGIN FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; if emp_rec.id = 7 then raise error; end if; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00 ')||' '||emp_rec.title); EXCEPTION when error then dbms_output.put_line('Dept Id is null for employee '||emp_rec.id); END; END LOOP; CLOSE c_emp; END; exception when others then dbms_output.put_line('xxxxxxxxxxxxxxxxxxxxxxx'); end; / // declare error begin DECLARE error exception; v_var1 number :='a'; CURSOR c_emp IS SELECT id, first_name, last_name,salary,title,dept_id FROM s_emp; emp_rec c_emp%rowtype; BEGIN OPEN c_emp; LOOP BEGIN FETCH c_emp INTO emp_rec; EXIT WHEN c_emp%NOTFOUND; if emp_rec.id = 7 then raise error; end if; dbms_output.put_line(rpad(emp_rec.id,2)||' '||rpad(emp_rec.last_name,17) ||' '||to_char(emp_rec.salary,'999,999.00 ')||' '||emp_rec.title); EXCEPTION when error then dbms_output.put_line('Dept Id is null for employee '||emp_rec.id); END; END LOOP; CLOSE c_emp; END; exception when others then dbms_output.put_line('xxxxxxxxxxxxxxxxxxxxxxx'); end; / -----------------------------------------------------------------------------------------------//Develop and store the function GET_ANNUAL_COMP, accepting parameter values for

// 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 basic formula to calculate the annua l salary // (salary * 12) + (commission_pct * salary * 12) create or replace function get_annual_comp( sal IN employees.salary%TYPE, comm IN employees.commission_pct%TYPE) RETURN NUMBER IS BEGIN RETURN (NVL(sal,0) *12 + (NVL(comm,0) * nvl(sal,0) * 12)); END get_annual_comp; / // Use the function in a SELECT statement against the EMPLOYEES table for employ ees in department 50 select employee_id, last_name, get_annual_comp(salary,commission_pct) "Annual Compensation" FROM employees Where department_id=50 //Create a procedure that returns a value from the SALARY and JOB_ID columns for a specified employee ID. // Compile the code and remove the syntax errors. create or replace procedure get_employee (empid IN employees.employee_id%TYPE, sal OUT employees.salary%TYPE, job OUT employees.job_id%TYPE) IS BEGIN select salary, job_id into sal, job from employees where employee_id =empid; END get_employee; / // Execute the procedure using host variables for the two OUT parameters, one fo r the salary and the //other for the job ID. Display the salary and job ID for employee ID 100. variable salary number variable job varchar2(15) execute get_employee(100, :salary, :job) print salary job // Invoke the procedure again, passing an EMPLOYEE_ID of 120. What happens and w hy? variable salary number variable job varchar2(15) execute get_employee(120, :salary, :job) print salary job /*BEGIN get_employee(120, :salary, :job); END; * ERROR at line 1:

ORA-01403: no data found ORA-06512: at "MANZER.GET_EMPLOYEE", line 6 ORA-06512: at line 1 There is no employee in the EMPLOYEES table with employee_id of 120. The select statement retrieved no data from the database, resulting in a fatal PL/SQL error : NO_DATA_FOUND. */ ------------------------------------------------------------------------------------------------------// CREATE a procedure, ADD_EMPLOYEE, to insert a new employee into the employees table. The procedure should call a valid // VALID_DEPTID function to check whether the department ID specified for the ne w employee exists in the DEPARTMENTS table //a. Create a function VALID_DEPTID to validate a specified department ID and re turns a BOOLEAN value of TRUE if the department exists CREATE OR REPLACE FUNCTION valid_deptid( deptid IN departments.department_id%TYPE) RETURN BOOLEAN IS dummy PLS_INTEGER BEGIN SELECT 1 INTO dummy FROM departments WHERE department_id = dept_id; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END valid_deptid; / // Create a procedure ADD_EMPLOYEE to add an employee to the employees table. Th e row should be added to the employees table // if the VALID_DEPTID function returns TRUE, otherwise alert the user with a me ssage. Provide the following parameters // (with DEFAULTS specified in parenthesis): first_name, last_name, email, job(S A_REP), mgr(100), sal(1000), comm(0), and deptid(20). // Use the EMPLOYEES_SEQ sequence to set the employee_id column, and set hire_da te to TRUNC(SYSDATE) CREATE OR REPLACE PROCEDURE add_employee( first_name employees.first_name%TYPE, last_name employees.last_name%TYPE, email employees.email%TYPE, job employees.job_id%TYPE DEFAULT 'SA_REP', mgr employees.manager_id%TYPE DEFAULT 149, sal employees.salary%TYPE DEFAULT 1000, comm employees.commission_pct%TYPE DEFAULT 0, deptid employees.department_id%TYPE DEFAULT 60) IS BEGIN IF valid_deptid(deptid) THEN INSERT INTO employees(employee_id, first_name, last_name, email, job_id, ma nager_id, hire_date, salary, commission_pct, department_id) VALUES(employees_seq.NEXTVAL, first_name, last_name, email, job, mgr, TRUNC (SYSDATE), sal, comm, deptid); ELSE RAISE_APPLICATION_ERROR(-20204, 'Invalid department ID. Try again.'); END IF; END add_employee;

/ // Call ADD_EMPLOYEE for the name Jane HArris in department 60, leaving other pa rmeters with their default values. EXECUTE add_employee('Jane', 'HArris', 'tom', deptid=> 60) //Using IN OUT parameters CREATE OR REPLACE PROCEDURE format_phone (phone_no IN OUT VARCHAR2) IS BEGIN phone_no := '(' || substr(phone_no,1,3) || ')' || substr(phone_no,4,3) || '-' || substr(phone_no,7) ; end format_phone; //calling the format_phone procedure VARIABLE phone_no VARCHAR2(15) EXECUTE :phone_no:= '8006789763' PRINT phone_no EXECUTE format_phone(:phone_no) PRINT phone_no ---------------------------------------------------------------------------------------// Show the department number, name, number of employees, and average salary of all departments, together with the names, salaries, and jobs of the employees // working in each department. SELECT d.department_id, d.department_name, count(e1.employee_id) employees, NVL(TO_CHAR(AVG(e1.salary), '99999.99'), 'No average' ) avg_s al, e2.last_name, e2.salary, e2.job_id FROM departments d RIGHT OUTER JOIN employees e1 ON d.department_id = e1.department_id RIGHT OUTER JOIN employees e2 ON d.department_id = e2.department_id GROUP BY d.department_id, d.department_name, e2.last_name, e2.salary, e2.job_id ORDER BY d.department_id, employees; DEPARTMENT_ID DEPARTMENT_NAME EMPLOYEES AVG_SAL LAST_NAME SALARY JOB_ID 20 Marketing 2 9500.00 Fay 6000 MK_REP 20 Marketing 2 9500.00 Hartstein 13000 MK_MAN 50 Shipping 5 4780.00 Vargas 4100 ST_CLERK 50 Shipping 5 4780.00 Mourgos 5800 ST_MAN 50 Shipping 5 4780.00 Rajs 5100 ST_CLERK 50 Shipping 5 4780.00 Matos 4200 ST_CLERK 50 Shipping 5 4780.00 Davies 4700 ST_CLERK 60 IT 7 3314.29 Hunold 9000 IT_PROG 60 IT 7 3314.29 Ernst 6000 IT_PROG 60 IT 7 3314.29 Lorentz 4200 IT_PROG 60 IT 28 3314.29 HArris 1000 SA_REP 80 Sales 4 9600.00 Taylor 8600 SA_REP 80 Sales 4 9600.00 Gietz 8300 AC_ACCOUNT 80 Sales 4 9600.00 Zlotkey 10500 SA_MAN 80 Sales 4 9600.00 Abel 11000 SA_REP 90 Executive 3 19333.33 Kochhar 17000 AD_VP 90 Executive 3 19333.33 De Haan 17000 AD_VP

90 Executive 3 19333.33 King 24000 AD_PRES 110 Accounting 1 12000.00 Higgins 12000 AC_MGR 0 No average Cores 10800 IT_Prog 0 No average Grant 7000 SA_REP 21 rows selected. // Create a report to display the department number and lowest salary of the dep artment with the highest average salary. SELECT department_id, MIN(salary) FROM employees GROUP BY department_id HAVING AVG(salary) = (SELECT MAX(AVG(salary)) FROM employees GROUP BY department_id); DEPARTMENT_ID MIN(SALARY) 90 17000 // Verify that tables are in the data dictionary SELECT table_name FROM user_tables //Verify the existence of the sequences in the data dictionary select sequence_name from user_sequences // Create a report that displays the jobs that are found in the Administration a nd Executive departments. Also display the number of employees // for these jobs. Show the job with the highest number of employees first. SELECT e.job_id, count(e.job_id) FREQUENCY FROM employees e JOIN departments d ON e.department_id = d.department_id WHERE d.department_name IN ('Administration', 'Executive') GROUP BY e.job_id ORDER BY FREQUENCY DESC; JOB_ID FREQUENCY AD_VP 2 AD_PRES 1

Potrebbero piacerti anche