ALTER TABLE TBNFS_PARCELAMENTO ADD DATA_COMPETENCIA DATE;
ALTER TABLE TBNFE_PARCELAMENTO ADD DATA_COMPETENCIA DATE; 

CREATE TRIGGER TTBNFS_PARCELAMENTO_B08I FOR TBNFS_PARCELAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE DATA_COMPETENCIA DATE;
BEGIN
  IF(NEW.NFS_CONTROLE > 0 AND NEW.DATA_COMPETENCIA IS NULL)THEN
  BEGIN
     DATA_COMPETENCIA = COALESCE((SELECT FIRST 1 A.DATA_COMPETENCIA FROM TBNFS A WHERE A.CONTROLE = NEW.NFS_CONTROLE),NEW.DATA_EMISSAO);
     NEW.DATA_COMPETENCIA = :DATA_COMPETENCIA;
  END

  IF(NEW.DATA_COMPETENCIA IS NULL)THEN
  BEGIN
     NEW.DATA_COMPETENCIA = NEW.DATA_EMISSAO;
  END
END;

CREATE TRIGGER TTBNFE_PARCELAMENTO_B06I FOR TBNFE_PARCELAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE DATA_COMPETENCIA DATE;
BEGIN
  IF(NEW.NFE_CONTROLE > 0 AND NEW.DATA_COMPETENCIA IS NULL)THEN
  BEGIN
     DATA_COMPETENCIA = COALESCE((SELECT FIRST 1 A.DATA_COMPETENCIA FROM TBNFE A WHERE A.CONTROLE = NEW.NFE_CONTROLE),NEW.DATA_ENTRADA);
     NEW.DATA_COMPETENCIA = :DATA_COMPETENCIA;
  END

  IF(NEW.DATA_COMPETENCIA IS NULL)THEN
  BEGIN
     NEW.DATA_COMPETENCIA = NEW.DATA_ENTRADA;
  END
END;


ALTER TABLE TBNFS_PARCELAMENTO ALTER DATA_COMPETENCIA DROP DEFAULT;
ALTER TABLE TBNFE_PARCELAMENTO ALTER DATA_COMPETENCIA DROP DEFAULT;