Archivo

Archive for 15 junio 2009

Certamen 2 PROGRAMA DE BASES DE DATOS (OCA DEVELOP) ORACLE PL/SQL

Este es el Certamen 2 de PROGRAMA DE BASES DE DATOS (OCA DEVELOP)

[ 1 ] Crear una tabla EMP , una función CAL_NEWSAL, los los procedimientos UPD_NEWSAL , NEW_EMP y el trigger VAL_SALARY
para insertar y actualizar datos de un empleado (55 pts)

1A Crear una tabla EMP con información a partir de una consulta que seleccione el
employee_id,first_name,last_name y salary de la tabla EMPLOYEES (4 pts)

CREATE TABLE emp AS
	SELECT EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY
	FROM employees;

1B Agrega a la tabla EMP dos nuevas columnas PERCENT de tipo NUMBER(8,2) y NEW_SALARY de tipo NUMBER de (8,2) (5 pts)

ALTER TABLE emp ADD percent NUMBER(8,2);
ALTER TABLE emp ADD new_salary NUMBER(8,2);

1C Crear una Funcion llamada CALL_NEWSAL que calcule el nuevo salario del empleado a partir del salariode éste
y un factor que representa el porcentaje en términos decimales. La formula para calcular el nuevo slario es: (6 pts)
(v_salary + ((v_salary – (v_salary * 12 * v_factor)) * v_factor))

CREATE OR REPLACE FUNCTION cal_newsal (v_salary IN employees.SALARY%TYPE,v_factor IN NUMBER) RETURN NUMBER
IS
BEGIN
	RETURN (v_salary + ((v_salary - (v_salary * 12 * v_factor)) * v_factor));
END cal_newsal;
/

1D CreValid Employee ID

CREATE OR REPLACE FUNCTION valid_employee(v_employee_id IN employees.EMPLOYEE_ID%TYPE) RETURN BOOLEAN
IS
	v_temporal VARCHAR(1);
BEGIN
	SELECT 'x'
	INTO v_temporal
	FROM emp
	WHERE EMPLOYEE_ID = v_employee_id;
	RETURN TRUE;
EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN FALSE;
END;
/

1D Crear un Procedimiento UPD_NEWSAL que permita actualizar, en la columna PERCENT el porcentaje de
incremento y en la columna NEW_SAL el nuevo incremento y en la columna NEW_SAL el nuevo salario. Para ello deberá pasar
el identificador del empleado y la función que calcula el nuevo salario creada en el punto anterior. En caso de actualizar
un empleado que no existe dse deberá informar lo ocurrido a través de un mensaje apropiado. Finalmente hacer los cambios permanentes.

CREATE OR REPLACE PROCEDURE upd_newsal(v_employee_id IN employees.EMPLOYEE_ID%TYPE,v_factor IN NUMBER)
IS
	empleado_salary employees.SALARY%TYPE;
BEGIN
	IF valid_employee(v_employee_id) THEN
		SELECT SALARY
		INTO empleado_salary
		FROM emp
		WHERE EMPLOYEE_ID = v_employee_id;

		UPDATE emp
		SET NEW_SALARY = cal_newsal (empleado_salary,v_factor)
		WHERE EMPLOYEE_ID = v_employee_id;
	ELSE
		RAISE_APPLICATION_ERROR(-20001,'ERROR: El id de Usuario No Existe');
	END IF;
END upd_newsal;
/

1E Testear el procedimiento UPD_NEWSAL para los empleados 100,105,110, con un factor de 0.01,0.02 y 0.03 correspondiente (3 pts)

SET SERVEROUTPUT ON
BEGIN
	upd_newsal(100,0.01);
END;
/
SET SERVEROUTPUT ON
BEGIN
	upd_newsal(105,0.05);
END;
/
SET SERVEROUTPUT ON
BEGIN
	upd_newsal(110,0.03);
END;
/

1F Crear un PROCEDIMIENTO NEW_EMP que permita para un nuevo empleado ingresar employee_id,first_name,last_name,salary,percent,new_salary,
para el new_salary utilizar la funcion cal_newsal. Conjuntamente deberá validar el salario, a través de un trigger de DML por fila llamado
VAL_SALARY que controle que el salario no debe exceder de 25.000 (18 pts)

CREATE OR REPLACE TRIGGER val_salary
BEFORE INSERT OR UPDATE OF SALARY
ON emp
FOR EACH ROW
BEGIN
	IF :new.SALARY > 25000 THEN
		RAISE_APPLICATION_ERROR(-20002,'ERROR: El salario sobrepasa los 25.000');
	END IF;
END val_salary;
/

SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE new_emp(v_employee_id 	IN employees.EMPLOYEE_ID%TYPE,
									v_first_name 	IN employees.FIRST_NAME%TYPE,
									v_last_name 	IN employees.LAST_NAME%TYPE,
									v_salary 		IN employees.SALARY%TYPE,
									v_percent 		IN NUMBER
									)
IS
	nuevoSalario NUMBER;
BEGIN
	IF valid_employee(v_employee_id) THEN
		DBMS_OUTPUT.PUT_LINE('ERROR: Ya Hay un usuario con esa ID');
	ELSE
		nuevoSalario := cal_newsal(v_salary,v_percent);
		INSERT INTO emp (EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY,PERCENT,NEW_SALARY)
		VALUES(	v_employee_id,
				v_first_name,
				v_last_name,
				v_salary,
				v_percent,
				nuevoSalario
				);
	END IF;

END new_emp;
/

1G TESTEAR EL PROCEDIMIENTO NEW_EMP Para los siguientes datos (2 pts)
Fila1:
employee_id:200, first_name: Albert,last_name: Einstein, salary: 20000, percent: 0.01, new_salary: cal_newsal
Fila2:
employee_id:300, first_name: Hilary,last_name: Clinton, salary: 26000, percent: 0.02, new_salary: cal_newsal

SET SERVEROUTPUT ON
BEGIN
	new_emp(200,'Albert','Einstein',20000,0.01);
END;
/

SET SERVEROUTPUT ON
BEGIN
	new_emp(300,'Hilary','Clinton',20000,0.02);
END;
/

1H Elimina tabla EMP (1 pts)

DROP TABLE emp;

1I Elimina Funcion cal_newSal (1 pts)

DROP FUNCTION cal_newsal;

1J Elimina Procedure upd_newsal (1 pts)

DROP PROCEDURE  upd_newsal;

1K Elimina Procedure new_emp (1 pts)

DROP PROCEDURE  new_emp;

1L Elimina Trigger val_salary (1 pts)

DROP TRIGGER val_salary;

[ 2 ] CREAR Y LLAMAR UN PACKAGE QUE CONTIENE CONSTRUCTORES PÚBLICOS Y PRIVADOS (45 pts)

2A Crear una tabla EMP con información, a partir de una consulta que seleccione el employee_id,first_name,
last_name y department_id de la tabla EMPLOYEES (4 pts)

CREATE TABLE emp AS
	SELECT EMPLOYEE_ID,FIRST_NAME,LAST_NAME,DEPARTMENT_ID
	FROM employees;

2B Crear una especificacion y un cuerpo de package llamado EMP_PACK que contiene un procedimiento
NEW_EMP como constructor público, y una función VALID_DEPT_ID como un constructor privado (29 pts)

CREATE OR REPLACE PACKAGE emp_pack IS
	PROCEDURE NEW_EMP(	v_employee_id IN employees.EMPLOYEE_ID%TYPE,
						v_first_name IN employees.FIRST_NAME%TYPE,
						v_last_name IN employees.LAST_NAME%TYPE,
						v_department_id IN employees.DEPARTMENT_ID%TYPE
					);
END emp_pack;
/
SET SERVEROUTPUT ON
CREATE OR REPLACE PACKAGE BODY emp_pack IS
	---------------------------------------------------------------------------------
	--	FUNCION PARA VALIDAR EL DEPARTAMENTO 						RETURN [BOOLEAN]
	---------------------------------------------------------------------------------
	FUNCTION VALID_DEPT_ID(v_id_depto IN employees.DEPARTMENT_ID%TYPE) RETURN BOOLEAN
	IS
		v_temporal VARCHAR(1);
	BEGIN
		SELECT 'x'
		INTO v_temporal
		FROM DEPARTMENTS
		WHERE DEPARTMENT_ID = v_id_depto;
		RETURN TRUE;
	EXCEPTION
		WHEN NO_DATA_FOUND THEN
			RETURN FALSE;
	END;
	---------------------------------------------------------------------------------
	--	PROCEDIMIENTO NEW_EMP
	---------------------------------------------------------------------------------
	PROCEDURE NEW_EMP(	v_employee_id IN employees.EMPLOYEE_ID%TYPE,
						v_first_name IN employees.FIRST_NAME%TYPE,
						v_last_name IN employees.LAST_NAME%TYPE,
						v_department_id IN employees.DEPARTMENT_ID%TYPE
					)
	IS
	BEGIN
		IF VALID_DEPT_ID(v_department_id) THEN
			INSERT INTO emp(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,DEPARTMENT_ID)
			VALUES(v_employee_id,v_first_name,v_last_name,v_department_id);
		ELSE
			DBMS_OUTPUT.PUT_LINE('ERROR: No existe Departamento');
		END IF;
	END;
END emp_pack;
/

2C Llamar al procedimiento NEW_EMP, utilizando como identificador de departamento el número 15. Como
el departamento 15 no existe en la tabla DEPARTMENT, se deberá desplegar un mensaje informando lo ocurrido (5 pts)

SET SERVEROUTPUT ON
BEGIN
	emp_pack.NEW_EMP(305,'Juan','Perez',15);
END;
/

2D Eliminar Tabla emp (1 pts)

DROP TABLE emp;

2E Eliminar funcion VALID_DEPT_ID (1 pts)

DROP FUNCTION emp_pack.VALID_DEPT_ID;

2F Eliminar procedimiento NEW_EMP (1 pts)

DROP PROCEDURE emp_pack.NEW_EMP;

2G Eliminar especificacion y cuerpo del package llamado EMP_PACK (1 pts)

DROP PACKAGE emp_pack;
Anuncios
Categorías:ORACLE, PL/SQL Etiquetas: , , , ,

ORACLE PL/SQL Repaso

Cursores:

	-- Declarar Cursor
	CURSOR emp_cursor IS
		SELECT last_name, department_id
		FROM employees;
	emp_record emp_cursor%ROWTYPE;

	-- Recorrer Secursar
	FOR emp_record IN emp_cursor LOOP --implicitamente abre y recupera la ocurrencia
     	IF emp_record.department_id = 80 THEN
			DBMS_OUTPUT.PUT_LINE(TO_CHAR(emp_record.department_id)||' '||emp_record.last_name);
		END IF;
   	END LOOP; -- implícitamente cierra la ocurrencia

Funciones

CREATE OR REPLACE FUNCTION g_job (p_jobid IN jobs.job_id%TYPE)
RETURN VARCHAR2
IS
	v_jobtitle jobs.job_title%TYPE;
BEGIN
	SELECT job_title
	INTO v_jobtitle
	FROM jobs
	WHERE job_id = p_jobid;
	RETURN (v_jobtitle);
EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN(NULL);
END g_job;
/
VARIABLE g_title VARCHAR2(30)
EXECUTE :g_title:= g_job('SA_REP')
PRINT g_title

Packages

CREATE OR REPLACE PACKAGE job_pack IS
	PROCEDURE add_job (p_job_id IN jobs.job_id%TYPE, p_job_title IN jobs.job_title%TYPE);
	PROCEDURE upd_job (p_job_id IN jobs.job_id%TYPE,p_job_title IN jobs.job_title%TYPE);
	PROCEDURE del_job (p_job_id IN jobs.job_id%TYPE);
	FUNCTION q_job    (p_job_id IN jobs.job_id%TYPE)RETURN VARCHAR2;
END job_pack;
/

CREATE OR REPLACE PACKAGE BODY job_pack IS
	PROCEDURE add_job (p_job_id IN jobs.job_id%TYPE, p_job_title IN jobs.job_title%TYPE) IS BEGIN
		INSERT INTO jobs(job_id, job_title)
		VALUES (p_jobid, p_jobtitle);
	END add_jobs;

	PROCEDURE upd_job (p_job_id IN jobs.job_id%TYPE, p_job_title 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;

	PROCEDURE del_job (p_job_id IN jobs.job_id%TYPE) IS BEGIN
		DELETE FROM jobs
		WHERE job_id = p_job_id;
		IF SQL%NOTFOUND THEN
			RAISE_APPLICATION_ERROR(-20203,'No job deleted');
		END IF;
	END del_job;

	FUNCTION q_job (p_jobid IN jobs.job_id%TYPE) RETURN VARCHAR2 IS
		v_jobtitle jobs.job_title%TYPE;
	BEGIN
		SELECT job_title
		INTO v_jobtitle
		FROM jobs
		WHERE job_id = p_jobid;
		RETURN (v_jobtitle);
	END q_job
END job_pack;
/	


Procedimientos

create or replace procedure procedimiento (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 procedimiento;
/

-- imprimir
VARIABLE g_sal NUMBER
VARIABLE g_job VARCHAR2(15)
EXECUTE procedimiento(120,:g_sal,:g_job)
PRINT g_sal
PRINT g_job


Triggers

create or replace trigger xxx
after update or insert or delete on employees for each row -- After:Antes
	   if updating  then

	elsif inserting then

	elsif deleting then

	end if;
end xxx;
/
Categorías:ORACLE, PL/SQL Etiquetas: , ,