CREATE OR REPLACE FUNCTION copy_ownername() RETURNS trigger AS '
 DECLARE
  fileid INTEGER;
 BEGIN
  IF new.accountfileownername = old.accountfileownername THEN
   RETURN NULL;
  END IF;
  FOR fileid IN (SELECT id FROM file WHERE fileownershipid = 3 AND setupaccountid = new.accountid) LOOP
   UPDATE file SET ownername = new.accountfileownername WHERE id = fileid;
  END LOOP;
  RETURN NULL;
 END
' LANGUAGE plpgsql;

CREATE TRIGGER copy_file_ownername AFTER UPDATE ON account FOR EACH ROW EXECUTE PROCEDURE copy_ownername();

