如何创建触发器功能?

时间:2018-05-14 12:25:14

标签: postgresql

如何创建触发器? 我在PostgreSQL的官方网站上发现了一篇文章,但我无法理解spjtrimns的含义。请帮帮我。

CREATE FUNCTION trigger_s_before_del () RETURNS trigger AS ' 
BEGIN 
if (select count(*) from spj a where trim(a.ns)=trim(OLD.ns))>0
then delete from spj where trim(spj.ns)=trim(OLD.ns); 
end if;
return OLD;
END; 
' LANGUAGE  plpgsql;

2 个答案:

答案 0 :(得分:0)

  • spj是一个表名
  • a是表格的别名,
  • ns是spj表中的列名,
  • trim是PostgreSQL内置函数。

答案 1 :(得分:0)

定义一个触发器,首先我们需要一种返回TRIGGER的特殊函数;

CREATE OR REPLACE FUNCTION "myTriggerFunction"() RETURNS TRIGGER AS $BODY$
DECLARE
    myVal BOOLEAN = TRUE;
BEGIN
    myVal = ( OLD."myField" > NEW."myField" );

    IF myVal THEN
        INSERT INTO "sampleRelatedTable"
            ( "id", "someField_old", "someField_new" )
        VALUES
            ( OLD."id", OLD."myField", NEW."myField" )
        ;
    END IF;

    RETURN NULL;
END;
$BODY$ LANGUAGE 'plpgsql' VOLATILE;

因为我们的"触发程序"准备好了,我们可以把它附在桌子上;

CREATE TRIGGER "myTrigger"
    UPDATE ON "myTable"
    FOR EACH ROW EXECUTE PROCEDURE "myTriggerFunction"()
;

现在我们的触发器准备好了。它会触发" myTriggerFunction"当记录在" myTable"已更新。

有关详细信息,请参阅docs;

TRIGGER程序:https://www.postgresql.org/docs/current/static/plpgsql-trigger.html CREATE TRIGGER:https://www.postgresql.org/docs/current/static/sql-createtrigger.html