更新/插入触发器之前的Postgresql似乎不起作用

时间:2011-10-07 14:12:36

标签: postgresql triggers plpgsql

我有以下触发功能:

CREATE OR REPLACE FUNCTION update_modelname_function()
  RETURNS trigger AS
$BODY$
BEGIN
  IF tg_op = 'INSERT' THEN
     new.model_name := upper(new.model_name);
     RETURN new;
  END IF;
  IF tg_op = 'UPDATE' THEN
     old.model_name := upper(old.model_name);
     RETURN new;
  END IF;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

我想要实现的是当列model_name的值在表中持久存在时始终是大写的。但似乎没有任何事情发生。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

您意外更新了old而不是new。尝试:

CREATE OR REPLACE FUNCTION update_modelname_function()
  RETURNS trigger AS
$BODY$
BEGIN
  IF tg_op = 'INSERT' THEN
     new.model_name := upper(new.model_name);
     RETURN new;
  ELSIF tg_op = 'UPDATE' THEN
     new.model_name := upper(new.model_name);
     RETURN new;
  END IF;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

如果示例显示整个代码,并且实际触发器仅在INSERT和/或UPDATE上触发,则可以进一步简化:

CREATE OR REPLACE FUNCTION update_modelname_function()
  RETURNS trigger AS
$BODY$
BEGIN

new.model_name := upper(new.model_name);
RETURN new;

END
$BODY$
  LANGUAGE plpgsql VOLATILE;