CREATE TRIGGER TTBCAIXABANCO_PREVISAO_B03I FOR TBCAIXABANCO_PREVISAO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
    IF(INSERTING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    
        if(new.DATA_COMPETENCIA is null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_PREVISAO);
        end
    END
    IF(UPDATING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    END
end;

ALTER TABLE TBCAIXABANCO_LANCAMENTO ADD DATA_COMPETENCIA DATE;

CREATE OR ALTER TRIGGER TTBCAIXABANCO_LANCAMENTO_B04I FOR TBCAIXABANCO_LANCAMENTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
    IF(INSERTING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    
        if(new.DATA_COMPETENCIA is null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_LANCAMENTO);
        end
    END
    IF(UPDATING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    END
end;

CREATE OR ALTER TRIGGER TTBCAIXABANCO_LANCAMENTO_B04D FOR TBCAIXABANCO_LANCAMENTO
ACTIVE BEFORE DELETE POSITION 8
AS
begin
   IF(OLD.MOVCONTMESTRE_ID > 0)THEN
   BEGIN
      DELETE FROM TBMOVCONTMESTRE WHERE ID = OLD.MOVCONTMESTRE_ID;
   END
end;