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

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