触发在表A上更新后更新表A中的特定列

时间:2014-03-01 11:58:07

标签: sql database postgresql triggers

我正在使用postgresql,我想通过总结表中的其他列来更新列。

  

EX:表名是A.当表1中的col1或col2或任何列值时   更新后,col6的值也应更新为   COL6 =(COL1 COL2 + + COL3)

为此我写了一个更新触发器如下。

CREATE FUNCTION update_total2() RETURNS TRIGGER AS $_$
BEGIN
    UPDATE hr_contract SET "x_TOTAL"=(NEW.x_othr_allow+NEW.x_med_allw+NEW."x_LTA"+NEW.wage+NEW.supplementary_allowance) WHERE id = OLD.id;
    RETURN OLD;
END $_$ LANGUAGE 'plpgsql';


CREATE TRIGGER hr_contract_after_update
    AFTER update ON hr_contract

    FOR EACH ROW
    EXECUTE PROCEDURE update_total2();

如下所示给出错误。

ERROR:  stack depth limit exceeded
HINT:  Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
CONTEXT:  SQL statement "SELECT 1 FROM ONLY "public"."res_users" x WHERE "id" OPERATOR(pg_catalog.=) $1 FOR SHARE OF x"
SQL statement "UPDATE hr_contract SET "x_TOTAL"=(NEW.x_othr_allow+OLD.x_med_allw+OLD."x_LTA"+OLD.wage+OLD.supplementary_allowance) WHERE id = OLD.id"
PL/pgSQL function update_total_result() line 3 at SQL statement
SQL statement "UPDATE hr_contract SET "x_TOTAL"=(NEW.x_othr_allow+OLD.x_med_allw+OLD."x_LTA"+OLD.wage+OLD.supplementary_allowance) WHERE id = OLD.id"

任何帮助都非常有用......

2 个答案:

答案 0 :(得分:2)

尝试检查该行是否有任何更改,并设置字段x_TOTAL的值(如果有):

CREATE FUNCTION update_total2() RETURNS TRIGGER AS $_$
  BEGIN
--Check if any of columns has been updated:
  if tg_op='UPDATE' and  old <> new then 
    NEW."x_TOTAL"= NEW.x_othr_allow+NEW.x_med_allw+NEW."x_LTA"+NEW.wage+NEW.supplementary_allowance);
  end if;

RETURN NEW;
END $_$ LANGUAGE 'plpgsql';

--Associate triger to table on BEFORE update events
CREATE TRIGGER hr_contract_after_update
    before update ON hr_contract

    FOR EACH ROW
    EXECUTE PROCEDURE update_total2();

Trigger documentation

答案 1 :(得分:1)

我不熟悉postgresql语法,但问题是您正在进行递归更新。您的函数update_total2不能对触发器上正在更新的同一个表使用UPDATE。

请查看文档以获取详细信息,您只需在触发器中执行以下操作:

FOR EACH ROW
    NEW.x_TOTAL = NEW.x_othr_allow + NEW.x_med_allw  + NEW."x_LTA" + NEW.wage + NEW.supplementary_allowance