如何在插入显示测试消息之前创建触发器功能

时间:2019-01-03 07:42:17

标签: postgresql plpgsql

我有一张桌子

CREATE TABLE test.emp (
  empname text,
  salary integer,
  last_date timestamp,
  last_user text
);

和功能

CREATE FUNCTION test.emp_stamp() RETURNS trigger AS $emp_stamp$
BEGIN
    -- Check that empname and salary are given
    IF NEW.empname IS NULL THEN
        RAISE EXCEPTION 'empname cannot be null';
    END IF;
    IF NEW.salary IS NULL THEN
        RAISE EXCEPTION '% cannot have null salary', NEW.empname;
    END IF;

    -- Who works for us when she must pay for it?
    IF NEW.salary < 0 THEN
        RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
    END IF;

    -- Remember who changed the payroll when
    NEW.last_date := current_timestamp;
    NEW.last_user := current_user;
    RETURN NEW;
END;
$emp_stamp$ LANGUAGE plpgsql;

如何显示消息,无需更新值我如何修改我的功能

触发是

CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON test.emp
   FOR EACH ROW EXECUTE PROCEDURE test.emp_stamp();

1 个答案:

答案 0 :(得分:0)

我认为您需要做的只是1)确保它是更新而不是插入(否则对packrat::snapshot的引用将没有任何意义,2)与现有记录进行比较。由于Employee名称似乎是PK,最后两个字段仅用于捕获更改,所以我猜您只想测试工资:

old

但是您当然也可以将其用于任何字段。如果您想确保至少进行了一次更改,那就是这样的:

-- Who works for us when she must pay for it?
IF NEW.salary < 0 THEN
    RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
elsif TG_OP = 'UPDATE' and new.salary = old.salary then
    RAISE EXCEPTION 'salary is already %', NEW.salary;
END IF;