Upcoming SlideShare
×

19,092 views

Published on

1 Comment
7 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• how to get employee salary by creating a function in pl/sql

Are you sure you want to  Yes  No
Views
Total views
19,092
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
1,175
1
Likes
7
Embeds 0
No embeds

No notes for slide

1. 1. PLSQL:1)Write a PL/SQL block to accept a year input and check whether it is a leap year.DECLAREv_YEAR NUMBER(4) := &P_YEAR;v_REMAINDER1 NUMBER(5,2);v_REMAINDER2 NUMBER(5,2);v_REMAINDER3 NUMBER(5,2);BEGINv_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 ) ORv_REMAINDER3 = 0) THENDBMS_OUTPUT.PUT_LINE(v_YEAR || is a leap year);ELSEDBMS_OUTPUT.PUT_LINE(v_YEAR || is not a leapyear);END IF;END;2)Write a PL/SQL block which will accept the employee number and print the annual_salary as well asthe 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 200019,999–10,000 1000<= 9,999 500DECLAREV_EMP_ID NUMBER := &EMPLOYEE_ID;V_SAL NUMBER(7,2);V_BONUS NUMBER(7,2);V_ANN_SALARY NUMBER(15,2);BEGINSELECT 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. 2. V_BONUS := 2000;ELSIF V_ANN_SALARY <= 19999 AND V_ANN_SALARY >=10000 THENV_BONUS := 1000;ELSEV_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 hiredate from the EMPLOYEES tableProcess each row from the cursor, and if the salary is greater than 15,000 and the hiredate is later than 01-FEB-1988, display the employee name, salary, and hire date inthe format shown in the following sample output:DECLARECURSOR C_EMP_CUR ISSELECT last_name,salary,hire_date FROM EMPLOYEES;V_ENAME VARCHAR2(25);v_SAL NUMBER(7,2);V_HIREDATE DATE;BEGINOPEN C_EMP_CUR;FETCH C_EMP_CUR INTO V_ENAME,V_SAL,V_HIREDATE;WHILE C_EMP_CUR%FOUNDLOOPIF V_SAL > 15000 AND V_HIREDATE >=TO_DATE(01-FEB-1988,DD-MON-YYYY) THENDBMS_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. 3. 4)Create a PL/SQL block to retrieve and output the last name and department ID of each employee from the EMPLOYEEStable 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 theprevious 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. Onearray 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 115DECLARETYPE Table_Ename IS table of employees.last_name%TYPEINDEX BY BINARY_INTEGER;TYPE Table_dept IS table of employees.department_id%TYPEINDEX BY BINARY_INTEGER;Tename Table_Ename;Tdept Table_dept;i BINARY_INTEGER :=0;CURSOR Namedept IS SELECT last_name,department_idFROM employees WHERE employee_id < 115;BEGINFOR emprec in NamedeptLOOPi := 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 substitutionvariable for the employee last name. Then, query the employees table for thelast_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 thatemployee’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 “duefor a raise,” similar to the following:
4. 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 MESSAGEAustin Not due for a raiseNayer Due for a raiseFripp Not due for a raiseKhoo Due for a raiseSET SERVEROUTPUT ON;DECLAREE_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);BEGINSELECT LAST_NAME,SALARY,HIRE_DATEINTO V_ENAME,V_SAL,V_HIREDATEFROM employees WHERE last_name = V_ENAME;V_YEARS := MONTHS_BETWEEN(SYSDATE,V_HIREDATE)/12;IF V_SAL < 3500 AND V_YEARS > 5 THENRAISE E_DUE_FOR_RAISE;ELSEDBMS_OUTPUT.PUT_LINE ( not due for a raise);END IF;EXCEPTIONWHEN E_DUE_FOR_RAISE THENBEGINDBMS_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. 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 theSQL Worksheet area, and then click the Run Script (F5) icon. This creates andcompiles 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 thepop-up menu.b) Invoke the procedure with IT_DBA as the job ID and DatabaseAdministrator 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 ofStock Manager. What happens and why?a)CREATE OR REPLACE PROCEDURE add_job(p_jobid jobs.job_id%type,p_jobtitle jobs.job_title%type) ISBEGIN 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 theJOB_ID column.7)7a. Create a procedure called UPD_JOB to update the job title. Provide the job ID anda new title using two parameters. Include the necessary exception handling if noupdate occurs.CREATE OR REPLACE PROCEDURE upd_job(p_jobid jobs.job_id%type,p_jobtitle jobs.job_title%type) ISBEGIN 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. 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 andview 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 IDIT_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 anemployee 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. Removesyntax 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 INjobs.job_id%type)RETURN jobs.job_title%type ISv_title jobs.job_title%type;BEGINSELECT job_titleINTO v_titleFROM jobsWHERE job_id = p_jobid;RETURN v_title;END get_job;/9b)Create a VARCHAR2 host variable called b_title, allowing a length of 35characters. Invoke the function with job ID SA_REP to return the value in thehost 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. 7. 10) Create a function called GET_ANNUAL_COMP to return the annual salary computedfrom an employee’s monthly salary and commission passed as parameters.10 a) Create the GET_ANNUAL_COMP function, which accepts parameter values for themonthly salary and commission. Either or both values passed can be NULL, butthe function should still return a non-NULL annual salary. Use the following basicformula 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 ISBEGINRETURN (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 foremployees in department 30.SELECT employee_id, last_name,get_annual_comp(salary,commission_pct) "AnnualCompensation"FROM employeesWHERE department_id=30/11)Create a procedure, ADD_EMPLOYEE, to insert a new employee into theEMPLOYEES table. The procedure should call a VALID_DEPTID function to checkwhether the department ID specified for the new employee exists in theDEPARTMENTS table.11a) Create a function called VALID_DEPTID to validate a specified department IDand 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 ISv_dummy PLS_INTEGER;BEGINSELECT 1INTO v_dummyFROM departmentsWHERE department_id = p_deptid;RETURN TRUE;EXCEPTIONWHEN NO_DATA_FOUND THENRETURN FALSE;END valid_deptid;
8. 8. 11b) Create the ADD_EMPLOYEE procedure to add an employee to the EMPLOYEEStable. The row should be added to the EMPLOYEES table if the VALID_DEPTIDfunction 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 DEFAULTSA_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)ISBEGINIF valid_deptid(p_deptid) THENINSERT 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);ELSERAISE_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 remainingparameters with their default values. What is the result?EXECUTE add_employee(Joe, Harris, JAHARRIS,p_deptid=> 80)
9. 9. 12)1) Create a package specification and body called JOB_PKG, containing a copy of yourADD_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 whencreating the package. You can copy the code in a procedure or function, and thenpaste the code into the appropriate section of the package.a) Create the package specification including the procedures and function headingsas public constructs.CREATE OR REPLACE PACKAGE job_pkg ISPROCEDURE add_job (p_jobid jobs.job_id%TYPE, p_jobtitlejobs.job_title%TYPE);PROCEDURE del_job (p_jobid jobs.job_id%TYPE);FUNCTION get_job (p_jobid IN jobs.job_id%type) RETURNjobs.job_title%type;PROCEDURE upd_job(p_jobid IN jobs.job_id%TYPE, p_jobtitleIN jobs.job_title%TYPE);END job_pkg;/SHOW ERRORSb) Create the package body with the implementations for each of the subprograms.CREATE OR REPLACE PACKAGE BODY job_pkg ISPROCEDURE add_job (p_jobid jobs.job_id%TYPE,p_jobtitle jobs.job_title%TYPE) ISBEGININSERT INTO jobs (job_id, job_title)VALUES (p_jobid, p_jobtitle);COMMIT;END add_job;PROCEDURE del_job (p_jobid jobs.job_id%TYPE) ISBEGINDELETE FROM jobsWHERE job_id = p_jobid;IF SQL%NOTFOUND THENRAISE_APPLICATION_ERROR(-20203, No jobsdeleted.);END IF;END DEL_JOB;FUNCTION get_job (p_jobid IN jobs.job_id%type)RETURN jobs.job_title%type ISv_title jobs.job_title%type;BEGINSELECT job_titleINTO v_titleFROM jobsWHERE 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) ISBEGIN
10. 10. UPDATE jobsSET job_title = p_jobtitleWHERE job_id = p_jobid;IF SQL%NOTFOUND THENRAISE_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 andSYSTEMS 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 containsthe following procedures and function that you created earlier:i) ADD_EMPLOYEE procedure as a public constructii) GET_EMPLOYEE procedure as a public construct iii) VALID_DEPTID function as a private constructCREATE OR REPLACE PACKAGE emp_pkg ISPROCEDURE 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 ISFUNCTION valid_deptid(p_deptid INdepartments.department_id%TYPE) RETURN BOOLEAN ISv_dummy PLS_INTEGER;BEGINSELECT 1INTO v_dummyFROM departmentsWHERE department_id = p_deptid;RETURN TRUE;EXCEPTIONWHEN NO_DATA_FOUND THENRETURN FALSE;
11. 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) ISBEGINIF valid_deptid(p_deptid) THENINSERT 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);ELSERAISE_APPLICATION_ERROR (-20204, Invaliddepartment 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) ISBEGINSELECT salary, job_idINTO p_sal, p_jobFROM employeesWHERE employee_id = p_empid;END get_employee;END emp_pkg;/b) Invoke the EMP_PKG.ADD_EMPLOYEE procedure, using department ID 15 foremployee Jane Harris with the email ID JAHARRIS. Because department ID 15does not exist, you should get an error message as specified in the exceptionhandler 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 foremployee David Smith with the email ID DASMITH.EXECUTE emp_pkg.add_employee(David, Smith,DASMITH,p_deptid => 80);14)