2013-04-25 71 views
0

我有兩個表部門和員工和這個顯示公司平均工資的PL/SQL語句。使用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 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; 

,我只是不知道如何在光標添加任何幫助將是巨大的地方有一個if語句!

+0

這個問題是完全可以解決沒有PL/SQL或需要循環通過遊標的結果集的方式... – Reimius 2013-04-26 18:41:35

回答

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; 
0

一個簡單的聲明會有所幫助。

10:17:37 [email protected]> 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 [email protected]>/

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

Elapsed: 00:00:00.09 

你也可以把它包在這樣的光標:

10:18:23 [email protected]> 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部門傳統上是那些有最低工資的一個。