ALTER TABLE TBNFE ADD DATA_COMPETENCIA DATE;
ALTER TABLE TBNFS ADD DATA_COMPETENCIA DATE;

CREATE OR ALTER TRIGGER TTBNFS_B09UI FOR TBNFS
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_EMISSAO);
        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 TTBNFE_B09UI FOR TBNFE
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_ENTRADA);
        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;