Practicas SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

2023

INSTITO TECNOLÓGICO DE
QUERÉTARO

ALUMNO:CRUZ CRISTALES
JOSÉ MANUEL

DOCENTE: Laura Lucia


Fernandez Romero

INGENIERÍA EN SISTEMAS
COMPUTACIONALES

PRACTICAS SQL
Practica 2
Note: Save your subprograms as .sql files, using the Save Script button.
Remember to set the SERVEROUTPUT on if you set it off previously.
1. Create and invoke the ADD_JOB procedure and consider the results.
a. Create a procedure called ADD_JOB to insert a new job into the
JOBS table. Provide the ID and title of the job, using two parameters.
CREATE OR REPLACE PROCEDURE add_job
(p_jobid IN
jobs.job_id%TYPE,p_jobtitle IN
jobs.job_title%TYPE)
IS
BEGIN
INSERT INTO jobs (job_id, job_title)
VALUES (p_jobid, p_jobtitle);
COMMIT;
END add_job;
b. Compile the code, and invoke the procedure with IT_DBA
as job ID and Database Administrator as job title.
Query the JOBS table to view the results.
In iSQL*Plus, load and run the script file created in question 1a above.
Procedure created.
EXECUTE add_job ('IT_DBA', 'Database Administrator')
SELECT * FROM jobs WHERE job_id = 'IT_DBA';

c. Invoke your procedure again, passing a job ID of ST_MAN and a job


title of Stock Manager. What happens and why?
EXECUTE add_job ('ST_MAN', 'Stock Manager')

There is a primary key integrity constraint on the JOB_ID column.


2. Create a procedure called UPD_JOB to modify a job in the JOBS table.
a. 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 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;

b. Compile the code; invoke the procedure to change the job title of the job ID IT_DBA to Data
Administrator. Query the JOBS table to view the results. Also check the exception
handling by trying to update a job that does not exist (you can use job ID IT_WEB and job title
Web Master).
In iSQL*Plus, load and run the script file created in the above question.
Procedure created.
EXECUTE upd_job ('IT_DBA', 'Data Administrator')
SELECT * FROM jobs WHERE job_id = 'IT_DBA';

EXECUTE upd_job ('IT_WEB', 'Web Master')

3. Create a procedure called DEL_JOB to delete a job from the JOBS table.
a. Create a procedure called DEL_JOB to delete a job from the JOBS table. Include the
necessary exception handling if no job is deleted.

SQL> CREATE OR REPLACE PROCEDURE upd_job


2 (p_jobid IN jobs.job_id%TYPE, p_jobtitle IN jobs.job_title%TYPE) IS
3 BEGIN
4 UPDATE jobs
5 SET job_title = p_jobtitle WHERE job_id = p_jobid;
6 IF SQL%NOTFOUND THEN
7 RAISE_APPLICATION_ERROR(-20202,'No job updated.'); END IF;
8 END upd_job;
9
10 /
a. Compile the code; invoke the procedure using job ID IT_DBA. Query the JOBS table to
view the results.
In iSQL*Plus, load and run the script file created in the above question.
Procedure created.
EXECUTE del_job ('IT_DBA')
SELECT * FROM jobs WHERE job_id = 'IT_DBA';

Also, check the exception handling by trying to delete a job that does not exist (use job ID
IT_WEB). You should get the message you used in the exception-handling section of the procedure
as output.
EXECUTE del_job ('IT_WEB')
4. Create a procedure called QUERY_EMP 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.
Use host variables for the two OUT parameters salary and job ID.
CREATE OR REPLACE PROCEDURE query_emp
(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 query_emp;

b. Compile the code, invoke the procedure to display the salary and job ID for employee ID 120.

In iSQL*Plus, load and run the script file created in the above question.
Procedure created.

VARIABLE g_sal NUMBER


VARIABLE g_job VARCHAR2(15)
EXECUTE query_emp (120, :g_sal, :g_job)
PRINT g_sal
PRINT g_job
c. Invoke the procedure again, passing an EMPLOYEE_ID of 300. What happens and why?
EXECUTE query_emp (300, :g_sal, :g_job)

There is no employee in the EMPLOYEES table with an EMPLOYEE_ID of 300. The SELECT
statement retrieved no data from the database, resulting in a fatal PL/SQL error,
NO_DATA_FOUND.
Practica 3

1. Create and invoke the Q_JOB function to return a job title.


a. Create a function called Q_JOB to return a job title to a host variable.
;

SQL> CREATE OR REPLACE FUNCTION q_job


2 (p_jobid IN jobs.job_id%TYPE) RETURN VARCHAR2
3 IS
4 v_jobtitle jobs.job_title%TYPE; BEGIN
5 SELECT job_title INTO v_jobtitle
6 FROM jobs
7 WHERE job_id = p_jobid; RETURN (v_jobtitle);
8 END q_job
9 /

a. Compile the code; create a host variable G_TITLE and invoke the function with job ID
SA_REP. Query the host variable to view the result.

In iSQL*Plus, load and run the script file created in the above question.
Function created.

VARIABLE g_title VARCHAR2(30)


EXECUTE :g_title := q_job ('SA_REP')

1. Create a function called ANNUAL_COMP to return the annual salary by accepting two parameters: an
employee’s monthly salary and commission. The function should address NULL values.
a. Create and invoke the function ANNUAL_COMP, passing in values for monthly salary and
commission. Either or both values passed can be NULL, but the function should still return an
annual salary, which is not NULL. The annual salary is defined by the basic formula:
(sal*12) + (commission_pct*salary*12)

CREATE OR REPLACE FUNCTION 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)* p_sal * 12));
END annual_comp;
/
b. Use the function in a SELECT statement against the EMPLOYEES table for department 80.

SELECT employee_id, last_name, annual_comp(salary,commission_pct)


"Annual Compensation"
FROM employees
WHERE department_id=80;

1. Create a procedure, NEW_EMP, to insert a new employee into the EMPLOYEES table. The procedure
should contain a call to the VALID_DEPTID function to check whether the department ID specified
for the new employee exists in the DEPARTMENTS table.
a. Create a function VALID_DEPTID to validate a specified department ID. The function should
return a BOOLEAN value.

SQL> CREATE OR REPLACE FUNCTION valid_deptid (p_deptid IN


departments.department_id%TYPE) RETURN BOOLEAN
2 IS
3 v_dummy VARCHAR2(1); BEGIN
4 SELECT 'x'
5 INTO v_dummy
6 FROM departments
7 WHERE department_id = p_deptid; RETURN (TRUE);
8 EXCEPTION
9 WHEN NO_DATA_FOUND THEN RETURN (FALSE);
10 END valid_deptid;
11 /

a. Create the procedure NEW_EMP to add an employee to the EMPLOYEES table. A new row should
be added to EMPLOYEES if the function returns TRUE. If the function returns FALSE, the
procedure should alert the user with an appropriate message.
Define DEFAULT values for most parameters. The default commission is 0, the default salary is
1000, the default department ID is 30, the default job is SA_REP and the default manager
number is 145. For the employee’s ID, use the sequence EMPLOYEES _SEQ. Provide the last
name, first name and e-mail for the employee.

SQL> CREATE OR REPLACE PROCEDURE new_emp


2 (p_lname employees.last_name%TYPE, p_fname
employees.first_name%TYPE, p_email employees.email%TYPE,
3 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)
4 IS BEGIN
5 IF valid_deptid(p_deptid) THEN
6 INSERT INTO employees(employee_id, last_name, first_name,
7 email, job_id, manager_id, hire_date, salary, commission_pct,
department_id)
8 VALUES (employees_seq.NEXTVAL, p_lname, p_fname, p_email, p_job, p_mgr,
TRUNC (SYSDATE, 'DD'), p_sal, p_comm, p_deptid);
9 ELSE
10 RAISE_APPLICATION_ERROR (-20204,
11 'Invalid department ID. Try again.');
12 END IF;
13 END new_emp;
14 /

Test your NEW_EMP procedure by adding a new employee named Jane Harris to department 15. Allow all other
parameters to default. What was the result?

EXECUTE new_emp(p_lname=>'Harris', p_fname=>'Jane',


p_email=>'JAHARRIS', p_deptid => 15)

a. Test your NEW_EMP procedure by adding a new employee named Joe Harris to department 80.
Allow all other parameters to default. What was the result?
EXECUTE new_emp(p_lname=>'Harris',p_fname=>'Joe',
p_email=>'JOHARRIS',p_deptno => 80)
PL/SQL procedure successfully completed.
Practica 5

1. Create a package specification and body called JOB_PACK. (You can save the package body and
specification in two separate files.) This package contains your ADD_JOB, UPD_JOB, and
DEL_JOB procedures, as well as your Q_JOB function.
Note: Use the code in your previously saved script files when creating the package.
a. Make all the constructs public.
Note: Consider whether you still need the stand-alone procedures and functions you just
packaged.

SQL> CREATE OR REPLACE PACKAGE job_pack IS


2 PROCEDURE add_job
3 (p_jobid IN jobs.job_id%TYPE, p_jobtitle IN
jobs.job_title%TYPE);
4 PROCEDURE upd_job
5 (p_jobid IN jobs.job_id%TYPE, p_jobtitle IN
jobs.job_title%TYPE);
6 PROCEDURE del_job
7 (p_jobid IN jobs.job_id%TYPE);
8 FUNCTION q_job
9 (p_jobid IN jobs.job_id%TYPE) RETURN VARCHAR2;
10 END job_pack;
11 /Package Created.
SQL> CREATE OR REPLACE PACKAGE BODY job_pack IS
2 PROCEDURE add_job
3 (p_jobid IN jobs.job_id%TYPE, p_jobtitle IN
jobs.job_title%TYPE)
4 IS BEGIN
5 INSERT INTO jobs (job_id, job_title) VALUES (p_jobid,
p_jobtitle);
6 END add_job;
7 PROCEDURE upd_job
8 (p_jobid IN jobs.job_id%TYPE, p_jobtitle IN
jobs.job_title%TYPE)
9 IS BEGIN
10 UPDATE jobs
11 SET job_title = p_jobtitle WHERE job_id = p_jobid;
12 IF SQL%NOTFOUND THEN
13 RAISE_APPLICATION_ERROR(-20202,'No job updated.'); END IF;
14 END upd_job;
15 PROCEDURE del_job
16 (p_jobid IN jobs.job_id%TYPE) IS
17 BEGIN
18 DELETE FROM jobs
19 WHERE job_id = p_jobid; IF SQL%NOTFOUND THEN
20 RAISE_APPLICATION_ERROR (-20203,'No job deleted.'); END IF;
21 END del_job;
22 FUNCTION q_job
23 (p_jobid IN jobs.job_id%TYPE) RETURN VARCHAR2
24 IS
25 v_jobtitle jobs.job_title%TYPE; BEGIN
26 SELECT job_title INTO v_jobtitle
27 FROM jobs
28 WHERE job_id = p_jobid; RETURN (v_jobtitle);
29 END q_job;
30 END job_pack;
31 /
a. Invoke your ADD_JOB procedure by passing values IT_SYSAN and SYSTEMS ANALYST
as parameters.
EXECUTE job_pack.add_job('IT_SYSAN', 'Systems Analyst')
PL/SQL procedure successfully completed.
b. Query the JOBS table to see the result.
SELECT * FROM jobs
WHERE job_id = 'IT_SYSAN';

2. Create and invoke a package that contains private and public constructs.
a. Create a package specification and package body called EMP_PACK that contains your
NEW_EMP procedure as a public construct, and your VALID_DEPTID function as a private
construct. (You can save the specification and body into separate files.)

SQL> CREATE OR REPLACE PACKAGE emp_pack IS


2 PROCEDURE new_emp
3 (p_lname
4 p_fname p_email employees.last_name%TYPE,
5 employees.first_name%TYPE, employees.email%TYPE,
6 p_job employees.job_id%TYPE DEFAULT 'SA_REP',
7 p_mgr employees.manager_id%TYPE DEFAULT 145,
8 p_sal employees.salary%TYPE DEFAULT 1000,
9 p_comm employees.commission_pct%TYPE DEFAULT 0, p_deptid
employees.department_id%TYPE DEFAULT 80);
10 END emp_pack;
11 /
Package Created.
If you have time:
3. a. Create a package called CHK_PACK that contains the procedures CHK_HIREDATE and
CHK_DEPT_MGR. Make both constructs public. (You can save the specification and body into
separate files.)
The procedure CHK_HIREDATE checks whether an employee’s hire date is within the following
range: [SYSDATE - 50 years, SYSDATE + 3 months].
Note:
• If the date is invalid, you should raise an application error with an appropriate message
indicating why the date value is not acceptable.
• Make sure the time component in the date value is ignored.
• Use a constant to refer to the 50 years boundary.
• A null value for the hire date should be treated as an invalid hire date.
The procedure CHK_DEPT_MGR checks the department and manager combination for a given
employee. The CHK_DEPT_MGR procedure accepts an employee ID and a manager
ID. The procedure checks that the manager and employee work in the same department.
The procedure also checks that the job title of the manager ID provided is MANAGER.
Note: If the department ID and manager combination is invalid, you should raise an application error
with an appropriate message.
CREATE OR REPLACE PACKAGE chk_pack IS
PROCEDURE chk_hiredate
(p_date in employees.hire_date%type);
PROCEDURE chk_dept_mgr
(p_empid in employees.employee_id%type,
p_mgr in employees.manager_id%type);
END chk_pack;
/
Package Created.
CREATE OR REPLACE PACKAGE BODY chk_pack IS

PROCEDURE chk_hiredate(p_date in employees.hire_date%TYPE)


IS
v_low date := ADD_MONTHS (SYSDATE, - (50 * 12));
v_high date := ADD_MONTHS (SYSDATE, 3);
BEGIN
IF TRUNC(p_date) NOT BETWEEN v_low AND v_high
OR p_date IS NULL THEN
RAISE_APPLICATION_ERROR(-20200,'Not a valid hiredate');
END IF;
END chk_hiredate;

PROCEDURE chk_dept_mgr(p_empid in employees.employee_id%TYPE,


p_mgr in employees.manager_id%TYPE)
IS
v_empnr employees.employee_id%TYPE;
v_deptid employees.department_id%TYPE;
BEGIN
BEGIN
SELECT department_id
INTO v_deptid
FROM employees
WHERE employee_id = p_empid;
EXCEPTION
WHEN NO_DATA_FOUND
THEN RAISE_APPLICATION_ERROR(-20000, 'Not a valid emp id');
END;
BEGIN
SELECT employee_id /*check valid combination
deptno/mgr for given employee */
INTO v_empnr
FROM employees
WHERE department_id = v_deptid
AND employee_id = p_mgr
AND job_id like '%MAN';

EXCEPTION
WHEN NO_DATA_FOUND
THEN RAISE_APPLICATION_ERROR (-20000,
'Not a valid manager for this department');
END;
END chk_dept_mgr;
END chk_pack;
/
Package Body Created.
b. Test the CHK_HIREDATE procedure with the following command:
EXECUTE chk_pack.chk_hiredate('01-JAN-47')
What happens, and why?

c. Test the CHK_HIREDATE procedure with the following command:


EXECUTE chk_pack.chk_hiredate(NULL)
What happens, and why?

d. Test the CHK_DEPT_MGR procedure with the following command:


EXECUTE chk_pack.chk_dept_mgr(117, 100)
What happens, and why?
Practica 6
1. Create a package called OVER_LOAD. Create two functions in this package, name each function
PRINT_IT. The function accepts a date or a character string and prints a date or a number, depending
on how the function is invoked.
Note:
• To print the date value, use DD-MON-YY as the input format, and
FmMonth,dd yyyy as the output format. Make sure you handle invalid input.
• To print out the number, use 999,999.00 as the input format.

The package specification:


CREATE OR REPLACE PACKAGE over_load IS
FUNCTION print_it(p_arg IN DATE)
RETURN VARCHAR2;
FUNCTION print_it(p_arg IN VARCHAR2)
RETURN NUMBER;
END over_load;
/
Package Created.

The package body:


CREATE OR REPLACE PACKAGE BODY over_load
IS
FUNCTION print_it(p_arg IN DATE)
RETURN VARCHAR2
IS
BEGIN
RETURN to_char(p_arg, 'FmMonth,dd yyyy');
END print_it;

FUNCTION print_it(p_arg IN VARCHAR2)


RETURN NUMBER
IS
BEGIN
RETURN TO_NUMBER(p_arg, '999,999.00');
-- or use the NLS characters for grands and decimals
-- RETURN TO_NUMBER(p_arg, '999G999D00');
END print_it;
END over_load;
/
Package Body Created.
a. Test the first version of PRINT_IT with the following set of commands:
VARIABLE display_date VARCHAR2(20)
EXECUTE :display_date := over_load.print_it('08-MAR-01')
PRINT display_date

b. Test the second version of PRINT_IT with the following set of commands:
VARIABLE g_emp_sal number
EXECUTE :g_emp_sal := over_load.print_it('33,600')
PRINT g_emp_sal

2. Create a new package, called CHECK_PACK, to implement a new business rule.


a. Create a procedure called CHK_DEPT_JOB to verify whether a given combination of department
ID and job is a valid one. In this case valid means that it must be a combination that currently
exists in the EMPLOYEES table.
Note:
• Use a PL/SQL table to store the valid department and job combination.
• The PL/SQL table needs to be populated only once.
• Raise an application error with an appropriate message if the combination is not valid.

CREATE OR REPLACE PACKAGE check_pack IS


PROCEDURE chk_dept_job
(p_deptid IN employees.department_id%TYPE,
p_job IN employees.job_id%TYPE);
END check_pack;
/
Package Created.
CRUZ CRISTALES JOSÉ MANUEL

Práctica 14: Controlar el acceso de usuarios

¿Qué privilegio se le debe otorgar a un usuario para iniciar sesión en Oracle


Server? ¿Se trata de un sistema o de un privilegio de objeto?
El privilegio del sistema CREATE SESSION
¿Qué privilegio se le debe otorgar a un usuario para crear tablas?
El Create Table
Si crea una tabla, ¿quién puede transferir privilegios a otros usuarios de la tabla?
cualquier persona a la que le haya dado esos privilegios mediante el uso de la OPCIÓN CON
CONCESIÓN.
¿Qué comando usas para cambiar tu contraseña?
El Alter User

Conceda a otro usuario acceso a la tabla DEPT. Pida al usuario que le conceda acceso de consulta a
su tabla DEPT.

GRANT select
ON dept
To < user1>

GRANT select
ON dept
To < user2>

1. Consulte todas las filas de la tabla DEPT.

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Agregue una nueva fila a la tabla DEP. El equipo 1 debe agregar Educación como departamento
número 50. El equipo 2 debe agregar Administración como departamento número 50. Haz
que los cambios sean permanentes.
CRUZ CRISTALES JOSÉ MANUEL

Cree un sinónimo para la tabla DEPT del otro equipo.


S QL> I NS ERT I NTO dep t (deptno, dname)
2VALUES(50,'Education');

Team2executesthisINSERTstatement.
SQL>INSERTINTOdept(deptno,dname)
2 VALUES (50 , 'Administration ' ) ;
SQL> COMMIT;

Consulte todas las filas de la tabla DEPT del otro equipo con su sinónimo.

Resultados de la instrucción SELECT del equipo 1.

SELECT
FROM dept;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Consulte el diccionario de datos USER_TABLES para ver información sobre las tablas de su
propiedad.
SQL> SELECT table_name
2FROM usertables;

TABLE_NAME
-----------------------
BONUS
CUSTOMER
DEPARTMENT
DEPT
CRUZ CRISTALES JOSÉ MANUEL

DUMMY
EMP
EMPLOYEE
ITEM
MY_EMPLOYEE
ORD
PRICE
PRODUCT
SALGRADE

Consulte la vista de diccionario de datos ALL_TABLES para ver información sobre todas las tablas
a las que puede acceder. Excluya las tablas que son de su propiedad.

TABLE_NAME OWNER
---------------------- ---------------
DEPT <user2>

Revocar el privilegio SELECT del otro equipo.

S Q L > S E L E C T t a b l e_ n a m e , o w n e r
2FROM *
3 WHERE owner != <your account>----------------------------------------------------
SQL> REVOKE select
2 ON dept
3 FROM u s e r 2 ;------------------------------------------------------------------------------
Team2revokestheprivilege.
SQL> REVOKE select
2 ON dept
3FROMuserl;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy