Postgresql函数停留在for循环中,查询永远不会结束查询

时间:2017-01-16 15:36:35

标签: postgresql plpgsql

该函数卡在for循环中,查询仍然在查询并且永远不会结束:

ALTER TABLE movement ADD COLUMN bar_id INTEGER;

CREATE OR REPLACE FUNCTION get_all_movement() RETURNS SETOF movement AS
$BODY$
DECLARE
barid INTEGER;
m movement%ROWTYPE;
BEGIN
 FOR m IN
  SELECT * FROM movement
 LOOP
 barid:= (SELECT bar_id FROM employee WHERE employee_id  = m.employee_id);
  UPDATE movement SET bar_id = barid;
  RETURN NEXT m;
 END LOOP;
 RETURN;
END
$BODY$
LANGUAGE 'plpgsql';

SELECT * FROM get_all_movement();

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您不需要函数和循环,更新语句将是最简单和最有效的:

update movement m
set bar_id = e.bar_id
from employee e
where m.employee_id = e.employee_id
returning m.*;

您的函数尝试在每一步中更新整个表。这可能会持续数小时,具体取决于数据量,更不用说结果不正确的事实。您忘记了WHERE声明中的UPDATE条款:

...
  UPDATE movement SET bar_id = barid
  WHERE employee_id = m.employee_id;
...