Postgres中过程/光标的逻辑问题

时间:2014-05-01 01:37:43

标签: postgresql plpgsql

我正在使用SQLFiddle进行分配以了解过程和游标。我知道游标不是最好用的,有更好的方法来完成我想做的事情,但我需要使用程序和游标。

我希望程序最终根据属于该部门的员工更新每个部门的Total_sal。

现在它没有这样做,而且我对Postgres没有足够的知识或经验来正确调试它。

updateSalary()过程之后的部门的Total_sal应如下所示:

dept_no    total_sal

10          7000
20          7000
30          6000

以下是我正在使用的小提琴:http://sqlfiddle.com/#!15/140d5/3

updatSalary过程如下:

CREATE OR REPLACE FUNCTION updateSalary() RETURNS VOID AS
$BODY$
  DECLARE 
  sum INTEGER := 0;
  dep CURSOR FOR SELECT Dno FROM Department;
  dep_row Department%ROWTYPE;
  emp CURSOR(dept_Dno INTEGER) FOR
    SELECT Dno, Salary FROM Employee WHERE Dno = dept_Dno;
  emp_row Employee%ROWTYPE;
BEGIN
  open dep;
  LOOP
    FETCH dep into dep_row;
      exit when NOT FOUND;
    open emp( dep_row.Dno );
    LOOP
      FETCH emp into emp_row;
        exit when NOT FOUND;
         sum := sum + emp_row.salary;
     END LOOP;
    UPDATE department SET total_sal = sum WHERE department.dno = emp_row.dno;
    close emp;
    sum := 0;
  END LOOP;
  close dep;
END;
$BODY$
  LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:1)

你应该使用'FOR ... IN ... LOOP'声明(Cursors in documentation, see 40.7.4.

CREATE OR REPLACE FUNCTION updateSalary() RETURNS VOID AS
$BODY$
  DECLARE 
  total INTEGER := 0;
  dep CURSOR FOR SELECT Dno FROM Department;
  dep_row Department%ROWTYPE;
  emp CURSOR(dept_Dno INTEGER) FOR
    SELECT Dno, Salary FROM Employee WHERE Dno = dept_Dno;
  emp_row Employee%ROWTYPE;
BEGIN
    FOR dep_row IN dep
    LOOP
        FOR emp_row IN emp( dep_row.Dno )
        LOOP
            total := total + emp_row.salary;
        END LOOP;
        UPDATE department SET total_sal = total WHERE department.dno = dep_row.dno;
        total := 0;
    END LOOP;
END;
$BODY$ LANGUAGE plpgsql;

sum 是聚合函数的名称;最好不要用作变量名)