Postgres中的函数和游标

时间:2014-04-30 17:20:16

标签: postgresql

我正在设计一个使用几个游标的函数,我是Postgres的新手,所以我不知道我正在制作的任何小的语法问题。我使用SQLFIDDLE来实现这一点,我收到的错误是:

Schema Creation Failed: ERROR: syntax error at or near "+": 

该功能如下所示,

CREATE OR REPLACE FUNCTION updateSalary() RETURNS VOID AS
$BODY$
DECLARE
  DECLARE sum INT DEFAULT 0;
  emp CURSOR FOR SELECT Dno, Salary FROM Employee;
  emp_row RECORD;
  dep CURSOR FOR SELECT Dno FROM Department;
  dep_row RECORD;
BEGIN
  open dep;
  LOOP
    FETCH dep into dep_row;
      exit when dep_row = null;
    open emp;
    LOOP
      FETCH emp into emp_row;
        exit when emp_row = null;
      if emp_row.Dno =dep_row.Dno then
        SET sum = sum + emp_row.salary;
      end if;

    END LOOP;
    UPDATE department SET total_sal = sum WHERE department.dno = emp_row.dno;
    close emp;
    SET sum = 0;
  END LOOP;
  close dep;
END;
$BODY$
  LANGUAGE plpgsql;

我相信这里有很多其他错误,所以如果有任何跳出来请告诉我,让我免受调试postgresql的美妙乐趣。

这是小提琴http://sqlfiddle.com/#!15/a1a45/3

由于某种原因,该功能未保存到该小提琴中。我认为为了让小提琴保存它必须能够建立起来。

1 个答案:

答案 0 :(得分:1)

下面提到几点

  1. 不需要游标......您只需在表employeedepartment之间进行联接。
  2. 以下是您应该尝试的内容

    CREATE OR REPLACE FUNCTION updateSalary() RETURNS VOID 
    AS
    $BODY$
      DECLARE sum INT DEFAULT 0;
    
    select sum = sum(emp.salary) 
    FROM Employee emp
    join Department dept
    on emp.Dno = dept.Dno;
    
        UPDATE department as d SET total_sal = sum 
        FROM employee as e    
        WHERE d.dno = e.dno;
    $BODY$
      LANGUAGE plpgsql;
    

    修改

    稍微修改了光标定义..试一试

    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 <-- change here
        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;
    

    您收到该错误导致未提及data type。我使用的是Parameterized Cursors