使用PL / SQL语句添加游标?

时间:2013-04-25 20:16:40

标签: sql oracle plsql

我有两个表部门和员工,以及显示公司平均工资的PL / SQL语句。

DECLARE
  v_cavg NUMBER;
BEGIN
  SELECT avg(salary) into v_cavg FROM employee;
  DBMS_Output.Put_Line('Company Average Salary: ' ||    RTRIM(TO_CHAR(v_cavg,'$999G999G999D99')));
  DBMS_Output.Put_Line('----------------------------------------');
END;

我现在要做的是实现游标并将员工和部门表连接在一起,以获得部门平均工资低于公司平均工资的所有部门名称。 我是游标的新手,我知道我必须在这些行的某个地方有一个if语句

if v_davg < v_cavg THEN
     DBMS_OUTPUT_.PUT_LINE ('Department Name: ' || RPAD(v_dname);
     DBMS_Output.Put_Line('Department Average Salary: ' ||    RTRIM(TO_CHAR(v_davg,'$999G999G999D99')));
  DBMS_Output.Put_Line('----------------------------------------');
else
     DBMS_Output.Put_Line(' '); /// Nothing here.
 END IF;
END;

我只是不确定如何添加光标任何帮助都会很棒!

2 个答案:

答案 0 :(得分:0)

您实际上不需要游标或IF语句:

SELECT d.name, avg(e.salary)
FROM department d, employee e
GROUP BY d.name
HAVING avg(e.salary) > v_cavg;

如果输出的格式很重要,您可以使用游标循环遍历这些结果,如下所示:

DECLARE

  CURSOR c IS
  SELECT...(as above);

BEGIN

  FOR r IN c LOOP
    dbms_output.put_line('Department Name: '||r.name);
    -- Etc, etc.
  END LOOP;

END;

答案 1 :(得分:0)

一个简单的陈述会有所帮助。

10:17:37 HR@sandbox> ed
Wrote file S:\tools\buffer.sql

  1  select d.department_name
  2    from departments d
  3         ,employees e
  4   where d.department_id = e.department_id
  5   group by d.department_name
  6*  having avg(salary) < (select avg(salary) from employees)
10:18:23 HR@sandbox> /

DEPARTMENT_NAME
------------------------------
Administration
Purchasing
IT
Shipping

Elapsed: 00:00:00.09

您也可以将其包装在这样的游标中:

10:18:23 HR@sandbox> ed
Wrote file S:\tools\buffer.sql

  1  begin
  2    for i in (
  3      select d.department_name
  4        from departments d
  5             ,employees e
  6       where d.department_id = e.department_id
  7       group by d.department_name
  8       having avg(salary) < (select avg(salary) from employees)
  9     ) loop
 10       dbms_output.put_line(i.department_name);
 11     end loop;
 12* end;
10:20:29  13  /
Administration
Purchasing
IT
Shipping

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.07

请注意,IT部门传统上是薪水最低的部门之一。