PostgreSQL:FOREIGN KEY / ON DELETE CASCADE / TRIGGER

时间:2016-12-29 15:15:55

标签: postgresql constraints

我有3张桌子:

详细

Detail_Archive

Transaction_Results

Transaction_Results是一个我没有构建的新表,并且有一个我可以完全删除的约束,但我相信它可能会破坏我认为它是为其构建的一些函数。

ALTER TABLE Transaction_Results
ADD Constraint Transaction_Results_Detail_DetailID_fkey FOREIGN KEY (DetailID)
REFERENCES Details (DetailID) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION

现在我过去只是简单地复制和删除了详细信息并删除了Detail_Archive

保持约束的最常见方式是什么? 我的想法是:可能使其为null,并将我删除的值设置为null,也许将它们移动到引用表的存档版本的另一列,并使其也为空。在我需要这个代码的代码中,我将不得不处理这个问题,但这对我来说并不是那么糟糕。

1 个答案:

答案 0 :(得分:0)

所以我采取了蛮力的方法。

ALTER TABLE Transaction_Results DROP CONSTRAINT Transaction_Results_Detail_DetailID_fkey ;
ALTER TABLE Transaction_Results ALTER COLUMN DetailID DROP NOT NULL;

 ALTER TABLE Transaction_Results ADD COLUMN DetailID_Archive integer NULL;

 CREATE OR REPLACE FUNCTION process_Detail_delete() RETURNS TRIGGER AS $Transaction_Results_trigger$
    BEGIN
        --
        -- Update a row in Transaction_Results to reflect the delete performed on Detail,
        -- make use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            UPDATE  Transaction_Results SET DetailID = NULL, DetailID_Archive =  OLD.DetailID where DetailID = OLD.DetailID ;
            RETURN OLD;

        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$Transaction_Results_trigger$ LANGUAGE plpgsql;

CREATE TRIGGER Transaction_Results_trigger
AFTER  DELETE ON [Detail]
   FOR EACH ROW EXECUTE PROCEDURE process_Detail_delete();​