DROP FUNCTION IF EXISTS ies.t_insured_policy_update CASCADE;
CREATE  FUNCTION ies.t_insured_policy_update()
RETURNS TRIGGER AS $$
BEGIN
   
	UPDATE ies.t_policy_summary t1
        SET lastname = NEW.lastname,
            firstname = NEW.firstname,
            patronymic = COALESCE(NEW.patronymic, 'НЕТ'),
            birthday = NEW.birhday,
            datebegin = NEW.datebegin,
            dateend = CASE WHEN t3.omstype = 2 THEN NEW.datestop ELSE COALESCE(NEW.datestop, NEW.dateend) END,
            sex = NEW.sex,
            smo = NEW.smo,
            insuredid = NEW.insured
        FROM ies.t_policy t3
        WHERE t3.policyid = NEW.policy
         AND NEW.insuredpolicyid = t1.policysummaryid;

    RETURN NEW; 
END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS t_insured_policy_after_update ON ies.t_insured_policy;
CREATE TRIGGER t_insured_policy_after_update
AFTER UPDATE OF lastname,firstname,patronymic,birhday,datebegin,dateend,datestop,sex,smo,insured ON ies.t_insured_policy
FOR EACH ROW EXECUTE FUNCTION ies.t_insured_policy_update();