【问题标题】:Postgresql trigger to insert a new record in table1 after an insert/update in table2Postgresql 触发器在 table2 中插入/更新后在 table1 中插入新记录
【发布时间】:2017-06-08 14:06:41
【问题描述】:

我有this 数据库,我需要回答以下问题:

"您需要创建一个触发器以及触发触发器时将执行的函数。每次检查患者并进行诊断时(如果插入的约会.diagnosis 不为空),患者的医疗文件夹将被更新。”

这是我想出的:

CREATE OR REPLACE FUNCTION appointmentsFunction() RETURNS TRIGGER AS $appointmentsfunction$ DECLARE appointment_patientamka BIGINT := new.patientamka; appointment_cure TEXT := new.cure; appointment_drug_id INT := drug_id; appointment_diagnosis TEXT := new.diagnosis; BEGIN IF appointment_diagnosis is NOT NULL THEN INSERT INTO public.medicalfolder (patient,cure,drug_id) VALUES (appointment_patientamka,appointment_cure, appointment_drug_id); END IF; RETURN NEW; END $appointmentsfunction$ LANGUAGE plpgsql;

最佳实践/最佳方法是什么?

附言。 patientamka 用作患者的 ID。它也可以是 patientID,但根据我老师的指导,它不是。

PS2.Medicalfolder 表可以包含同一患者的重复记录。所以,我不必用病人的 id (patientamka) 更新记录,我只需要插入一个新的。

【问题讨论】:

    标签: postgresql function triggers insert


    【解决方案1】:

    这更像是一个代码审查问题,因为我假设上述方法有效,但无论如何:

    appointmentsFunction()

    PG 中的命名约定是snake_case 而不是camelCase。也无需将“函数”一词附加到您的函数中。称它为描述其功能的东西。

    DECLARE
        appointment_patientamka BIGINT := new.patientamka;
        appointment_cure TEXT := new.cure;
        appointment_drug_id INT := drug_id;
        appointment_diagnosis TEXT := new.diagnosis;
    

    我有两个问题。

    首先,您将了解为四个变量赋值的成本(成本很小,但不是免费的)。然后检查其中一个是否为 NULL,如果是,则不使用这些值 - 因此您浪费了读取和分配所有这些变量的努力。

    第二件事是这些变量都不是必需的,因为您可以检查 NEW.diagnosis 是否为 NULL,如果不是,则将值(直接从 NEW 读取)插入到 medicalfolder

    最后,将BEGINDECLAREEND 放在同一个缩进上会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      相关资源
      最近更新 更多