DROP FUNCTION IF EXISTS akuz.change_patient_fio CASCADE;

CREATE FUNCTION akuz.change_patient_fio()
  RETURNS trigger AS
$BODY$
BEGIN
	UPDATE akuz.T_PATIENT
	SET FIO = REPLACE(New.LastName || CHR(160) || New.FirstName || coalesce(CHR(160) || New.FatherName, CHR(160)), 'ё', 'е')
	where PatientID = New.PatientID;
Return New;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
--ALTER FUNCTION akuz.change_patient_fio() OWNER TO postgres;

CREATE TRIGGER patient_fio
  AFTER INSERT OR UPDATE OF lastname, firstname, fathername
  ON akuz.t_patient
  FOR EACH ROW
  EXECUTE PROCEDURE akuz.change_patient_fio();
