Sentencia Select /: Introducción A SQL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Introducción a SQL

/* Sentencia Select */
SELECT empno, ename, sal, job FROM emp;

/* Estructura de Tabla */
DESCRIBE emp;
DESC emp;

/* Operadores de Comparación */
SELECT ename, sal, comm FROM emp WHERE sal <= comm;
SELECT ename, sal FROM emp WHERE sal BETWEEN 1000 AND 1500;
SELECT ename, sal, mgr FROM emp WHERE mgr IN
(7902,7566,7788);
SELECT ename FROM emp WHERE ename LIKE '_A%';
SELECT ename, job, comm FROM emp WHERE comm IS NULL;
//Los campos donde el campo comm Esta vacio

/* Operadores Lógicos */
SELECT ename, job, sal FROM emp WHERE sal >=1100 AND
job='CLERK';

SELECT ename, job, sal FROM emp WHERE sal >=1100 OR


job='CLERK';
SELECT ename, job FROM emp WHERE job NOT IN ('CLERK',
'MANAGER', 'ANALYST');

/* Order By */
SELECT empno, ename, sal*12 as salario FROM emp ORDER BY
salario DESC;

Que nos muestre con cierto orden descendente y ascendente

/* Alias */
SELECT A.empno, A.ename FROM emp A ORDER BY A.ename DESC;
SELECT a.empno as codigo, a.ename as nombre FROM emp A ORDER
BY a.sal DESC;
SELECT a.empno codigo, a.ename nombre FROM emp A ORDER BY
sal DESC;

/* Funciones de Caracter */
SELECT LOWER(ename) FROM emp;
Pasa a minusculas

SELECT INITCAP(dname) FROM dept;


La primera a mayuscula
SELECT LENGTH(loc) FROM dept;

SELECT LPAD(sal,10,'*') FROM emp;


SELECT INSTR('Amigos','g') FROM dual;

/* Funciones Numéricas */
SELECT ROUND(sal/3,2) FROM emp;
SELECT TRUNC(sal/3,2) FROM emp;

/* Funciones de Fecha */
SELECT SYSDATE,ADD_MONTHS(SYSDATE,4)
AGREGAR_MES,NEXT_DAY(SYSDATE,1)
AGREGAR_SEMANA,LAST_DAY(sysdate) ULTIMO FROM DUAL;

/* Funciones de Conversión */
SELECT TO_CHAR(sal,'$009,999.99') from emp;
SELECT TO_CHAR(hiredate,'dd/mm/yyyy') from emp;
SELECT TO_CHAR(hiredate,'month') from emp;
SELECT TO_CHAR(hiredate,'DAY') from emp;

/* Función NVL */
SELECT NVL(comm,0) FROM emp;
SELECT NVL(hiredate,sysdate) FROM emp;
SELECT NVL(job,'no job') FROM emp;

/* Joins */
SELECT a.ename, a.job, a.sal, b.dname FROM emp a, dept b
WHERE a.deptno = b.deptno;
SELECT a.* FROM emp a, salgrade b WHERE a.sal BETWEEN b.losal
and b.hisal;
SELECT nvl(a.ename,'<VACIO>') ename,NVL(a.sal,0.00)
SAL,A.DEPTNO,NVL(b.dname,'NULL') FROM emp a,dept b WHERE
a.deptno = b.deptno (+);
SELECT nvl(a.ename,'<VACIO>') ename,NVL(a.sal,0.00)
SAL,NVL(A.DEPTNO,0) DEPTNO,NVL(b.dname,'NULL') FROM emp
a,dept b WHERE a.deptno (+) = b.deptno;
SELECT a.ename EMPLEADO,a.sal SALARIO,a.job OCUPACION,m.ename
MANAGER FROM emp a,emp m WHERE a.mgr = m.empno and
a.empno=7369;

/* Funciones de Grupo */
SELECT deptno,AVG(sal) FROM emp GROUP BY deptno;
SELECT deptno,job,sum(sal) FROM emp GROUP BY deptno, job;
SELECT deptno,job,sum(sal) FROM emp GROUP BY
ROLLUP(deptno,job);
SELECT deptno,job,sum(sal) FROM emp GROUP BY CUBE (deptno,
job);
/* Having */
SELECT deptno, job, sum(sal) FROM emp GROUP BY deptno, job
HAVING sum(sal)>2500;

/* Subconsultas */
SELECT ename,sal FROM emp WHERE sal > (SELECT sal FROM emp
WHERE empno=7566);
SELECT ename,sal,deptno FROM emp WHERE sal IN (SELECT
min(sal) FROM emp GROUP BY deptno) ;
SELECT ename,sal,deptno FROM emp WHERE (deptno,sal) IN
(SELECT deptno,min(sal) FROM emp GROUP BY deptno);

/* Sentencia Insert */
INSERT INTO emp VALUES
(2296,'AROMANO','SALESMAN',7782,to_date('03/02/1997',
'dd/mm/yyyy'),1300,NULL,10);
INSERT INTO dept (deptno,dname,loc) VALUES
(&departamento,'&Nombre','&Localizacion');
ACCEPT depto_id prompt 'Ingrese número dpto: ';
ACCEPT name_id prompt 'Ingrese nombre dpto: ';
INSERT INTO dept (deptno,dname) VALUES
(&depto_id,'&name_id');
INSERT INTO bonus (ename,job,sal,comm) SELECT
ename,job,sal,comm FROM emp WHERE job = 'MANAGER';

/* Sentencia Update */
UPDATE emp SET deptno = 20 WHERE empno=7782;
UPDATE emp SET (job,deptno) = (SELECT job,deptno FROM emp
WHERE empno = 7788) WHERE empno = 7698;
UPDATE emp SET deptno = (SELECT deptno FROM emp WHERE empno =
7788) WHERE job = (SELECT job FROM emp WHERE empno = 7788 ) ;

/* Sentencia Delete */
DELETE FROM dept WHERE dname = 'RESEARCH';
DELETE FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE
dname = 'SALES');

/* Sentencia Truncate */
TRUNCATE TABLE bonus;

/* Sentencia Merge */
MERGE INTO bonus D
USING (SELECT ename,job,sal,comm FROM emp WHERE deptno = 30)
S
ON (D.ename = S.ename)
WHEN MATCHED THEN UPDATE SET D.comm = S.sal*1.25
WHEN NOT MATCHED THEN INSERT (D.ename,D.job,D.sal,D.comm)
VALUES (S.ename,S.job,S.sal,S.sal*1.25);
Introducción a PL/SQL

/* Ejercicio Nº 1 */

SET SERVEROUTPUT ON;


DECLARE
CURSOR c_datos IS SELECT deptno,dname FROM dept;
vdeptno NUMBER(2);
vdname VARCHAR2(14);
BEGIN
OPEN c_datos;
LOOP
FETCH c_datos INTO vdeptno,vdname;
EXIT WHEN c_datos%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( 'codigo: ' || vdeptno ||
' ... nombre: '||vdname) ;
END LOOP;
CLOSE c_datos;
END;

/* Ejercicio Nº 2 */

SET SERVEROUTPUT ON;


DECLARE
CURSOR c_datos IS SELECT deptno,dname FROM dept;
vdeptno NUMBER(2);
vdname VARCHAR2(14);
BEGIN
OPEN c_datos;
FETCH c_datos INTO vdeptno,vdname;
WHILE c_datos%FOUND LOOP
DBMS_OUTPUT.PUT_LINE( 'codigo: ' || vdeptno ||
' ... nombre: '||vdname) ;
FETCH c_datos INTO vdeptno,vdname;
END LOOP;
CLOSE c_datos;
END;

/* Ejercicio Nº 3 */

SET SERVEROUTPUT ON;


DECLARE
CURSOR c_datos IS SELECT deptno,dname FROM dept;
vdeptno NUMBER(2);
vdname VARCHAR2(14);
BEGIN
OPEN c_datos;
DBMS_OUTPUT.PUT_LINE( c_datos%rowcount );
FETCH c_datos INTO vdeptno,vdname;
DBMS_OUTPUT.PUT_LINE( c_datos%rowcount );
WHILE c_datos%FOUND LOOP
DBMS_OUTPUT.PUT_LINE( 'codigo: ' || vdeptno ||
' ... nombre: '||vdname) ;
FETCH c_datos INTO vdeptno,vdname;
END LOOP;
DBMS_OUTPUT.PUT_LINE( c_datos%rowcount );
CLOSE c_datos;
END;

/* Ejercicio Nº 4 */

SET SERVEROUTPUT ON;


DECLARE
CURSOR c_datos IS SELECT deptno,dname FROM dept;
vdeptno NUMBER(2);
vdname VARCHAR2(14);
BEGIN
IF c_datos%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE( 'cursor abierto' );
ELSE
DBMS_OUTPUT.PUT_LINE( 'cursor cerrado' );
END IF;
OPEN c_datos;
IF c_datos%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE( 'cursor abierto' );
ELSE
DBMS_OUTPUT.PUT_LINE( 'cursor cerrado' );
END IF;
FETCH c_datos INTO vdeptno,vdname;
WHILE c_datos%FOUND LOOP
DBMS_OUTPUT.PUT_LINE( 'codigo: ' || vdeptno ||
' ... nombre: '||vdname) ;
FETCH c_datos INTO vdeptno,vdname;
END LOOP;
CLOSE c_datos;
IF c_datos%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE( 'cursor abierto' );
ELSE
DBMS_OUTPUT.PUT_LINE( 'cursor cerrado' );
END IF;
END;
/* Ejercicio Nº 5 */

SET SERVEROUTPUT ON;


DECLARE
CURSOR c_datos IS SELECT deptno,dname FROM dept;
BEGIN
FOR v_datos IN c_datos LOOP
DBMS_OUTPUT.PUT_LINE( 'codigo: ' ||
v_datos.deptno || ' ... nombre: '||v_datos.dname) ;
END LOOP;
END;

/* Ejercicio Nº 6 */

SET SERVEROUTPUT ON;


BEGIN
DELETE FROM emp WHERE empno=9999;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE( 'No existe empleado' ) ;
END IF;
END;

/* Ejercicio Nº 7 */

SET SERVEROUTPUT ON;


DECLARE
v_ename varchar2(14);
BEGIN
SELECT ename INTO v_ename FROM emp WHERE empno=7902;
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE( 'Si existe empleado' ) ;
END IF;
END;

/* Ejercicio Nº 8 */

SET SERVEROUTPUT ON;


BEGIN
update emp set hiredate=sysdate WHERE deptno='30';
DBMS_OUTPUT.PUT_LINE( 'Lineas afectadas : ' || SQL
%ROWCOUNT ) ;
commit;
END;
/* Ejercicio Nº 9 */

SET SERVEROUTPUT ON;


DECLARE
v_dname varchar2(14);
BEGIN
SELECT dname INTO v_dname FROM dept WHERE deptno
between 10 and 30;
--SELECT dname INTO v_dname FROM dept WHERE deptno
between 80 and 90;
DBMS_OUTPUT.PUT_LINE( 'Lineas afectadas : ' || SQL
%ROWCOUNT ) ;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Hay mas de un
registro!!!!!');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No hay datos!!!!');
END;

/* Ejercicio Nº 10 */

SET SERVEROUTPUT ON;


DECLARE
v_cnt varchar2(14);
mierror EXCEPTION;
BEGIN
SELECT count(*) INTO v_cnt FROM dept;
IF v_cnt>1 THEN
raise mierror;
ELSE
DBMS_OUTPUT.PUT_LINE( '1 Departamento' );
END IF;
EXCEPTION
WHEN mierror THEN
DBMS_OUTPUT.PUT_LINE('Error de usuario!!!!!');
END;
Create table auditoria (usuario varchar2(20), fechamod date,
accion varchar2(10));

Desarrollar un paquete que permita darle mantenimiento a la


tabla dept (crear un procedimiento para cada acción de
actualización). Crear un disparador que permita auditar las
acciones realizadas en la tabla Dep. (Tabla auditoria).
Ejecutar los procedimientos a través de un bloque PL/SQL en
SQL*PLUS.
Create table auditoria (usuario varchar2(20), fechamod date,
accion varchar2(10));

Desarrollar un paquete que permita darle mantenimiento a la


tabla dept (crear un procedimiento para cada acción de
actualización). Crear un disparador que permita auditar las
acciones realizadas en la tabla Dep. (Tabla auditoria).
Ejecutar los procedimientos a través de un bloque PL/SQL en
SQL*PLUS.

You might also like