CREATE OR REPLACE FUNCTION iszl.Change_INSURED_POLICY_RECORD_fio()
  RETURNS trigger AS
$BODY$
BEGIN
	UPDATE iszl.T_INSURED_POLICY_RECORD
	SET FIO = REPLACE(LOWER(New.LastName) || CHR(160) || LOWER(New.FirstName) || coalesce(CHR(160) || LOWER(New.Patronymic), CHR(160)), 'ё', 'е')
	where InsuredPolicyRecordID = New.InsuredPolicyRecordID;
	Return New;
END;
$BODY$
LANGUAGE  plpgsql;

DO 
$$ 
BEGIN 
if not exists(select * from information_schema.triggers WHERE event_object_table = 't_insured_policy_record' AND trigger_name = 'insured_policy_record_fio') 
then
	CREATE TRIGGER INSURED_POLICY_RECORD_fio
		After INSERT OR UPDATE of LastName, FirstName, Patronymic
		ON ISZL.T_INSURED_POLICY_RECORD
		FOR EACH ROW
		EXECUTE PROCEDURE iszl.Change_INSURED_POLICY_RECORD_fio();
end if; 
END
$$ LANGUAGE  plpgsql;
