CREATE TRIGGER APPLICATION_UPDATE BEFORE UPDATE ON APPLICATION

FOR EACH ROW

BEGIN
  DECLARE APP_STATUS VARCHAR(32);
  DECLARE APP_FINISH_DATE DATETIME;

  SELECT APPLICATION.APP_STATUS into @APP_STATUS FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1;

  IF(OLD.APP_STATUS<>NEW.APP_STATUS) THEN
    SET @APP_STATUS = NEW.APP_STATUS;
    UPDATE APP_CACHE_VIEW SET APP_STATUS = @APP_STATUS WHERE APP_UID = NEW.APP_UID;
  END IF;

  IF(OLD.APP_DATA<>NEW.APP_DATA) THEN
      UPDATE APP_CACHE_VIEW SET APP_UPDATE_DATE = NEW.APP_UPDATE_DATE WHERE APP_UID = NEW.APP_UID;
  END IF;

  IF (NEW.APP_STATUS = 'COMPLETED') THEN
      UPDATE APP_CACHE_VIEW SET APP_FINISH_DATE = NEW.APP_FINISH_DATE WHERE APP_UID = NEW.APP_UID;
      UPDATE APP_CACHE_VIEW SET APP_UPDATE_DATE = NEW.APP_UPDATE_DATE WHERE APP_UID = NEW.APP_UID;
  END IF;
END
