游标习题

--编写一个PL/SQL块,输出所有员工的姓名。员工号。工资和部门号。
Select * from emp;
Select * from dept;

--简单循环
set serveroutput on
DECLARE
  CURSOR c_emp IS SELECT * FROM emp;
  v_emp emp%ROWTYPE;
BEGIN 
  OPEN c_emp;
  LOOP 
    FETCH c_emp INTO v_emp;
    EXIT WHEN c_emp%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_emp.ename||' '||v_emp.empno||' '||v_emp.sal||' '||v_emp.deptno);
  END LOOP;
  CLOSE c_emp;
END;

--while循环
set serveroutput on
DECLARE
  CURSOR c_emp IS SELECT * FROM emp;
  v_emp emp%ROWTYPE;
BEGIN 
  OPEN c_emp;
  FETCH c_emp INTO v_emp;
  
  WHILE c_emp%FOUND LOOP
    DBMS_OUTPUT.PUT_LINE(v_emp.ename||' '||v_emp.empno||' '||v_emp.sal||' '||v_emp.deptno);
    FETCH c_emp into v_emp;
  END LOOP;
  
  CLOSE c_emp;
END;

--for循环
set serveroutput on
DECLARE
  CURSOR c_emp IS SELECT * FROM emp;
BEGIN 

  FOR i IN c_emp LOOP
  DBMS_OUTPUT.PUT_LINE(i.ename||' '||i.empno||' '||i.sal||' '||i.deptno);
  END LOOP;
  
END;

--编写一个PL/SQL块,输出所有比本部门平均工资高的员工信息
set serveroutput on
DECLARE
  CURSOR c_emp IS select * from emp where sal>(select avg(sal) from emp);
BEGIN 

  FOR i IN c_emp LOOP
  DBMS_OUTPUT.PUT_LINE(i.ename||' '||i.empno||' '||i.sal||' '||i.deptno);
  END LOOP;
  
END;

set serveroutput on
DECLARE
  CURSOR c_emp IS select * from emp where sal>(select avg(sal) from emp where deptno in (select distinct deptno from emp group by deptno));
BEGIN 

  FOR i IN c_emp LOOP
  DBMS_OUTPUT.PUT_LINE(i.ename||' '||i.empno||' '||i.sal||' '||i.deptno);
  END LOOP;
  
END;

--编写一个PL/SQL块,输出所有员工及其部门领导的姓名,员工号,部门号
set serveroutput on
DECLARE
  CURSOR c_emp IS 
  select e1.empno,e1.ename,e2.ename as mrg_name,e2.empno as mrg_no,e2.deptno as mrg_deptno from emp e1 inner join emp e2 on e1.mgr = e2.empno;
BEGIN 

  FOR i IN c_emp LOOP
  DBMS_OUTPUT.PUT_LINE(i.empno||' '||i.ename||' '||i.mrg_name||' '||i.mrg_no||' '||i.mrg_deptno);
  END LOOP;
  
END;

你可能感兴趣的:(游标习题)