CREATE OR ALTER TRIGGER TTBCENTRO_DE_CUSTO_B06U FOR TBCENTRO_DE_CUSTO
ACTIVE BEFORE UPDATE POSITION 2
AS
declare variable ID INTEGER;
begin
 ID = 0;
 IF(OLD.STATUS <> NEW.STATUS AND NEW.STATUS = '0') THEN
 BEGIN
    ID = COALESCE((SELECT FIRST 1 A.ID FROM TBCCUSTO_COTA A WHERE A.CCUSTO = OLD.CODIGO AND A.MES = EXTRACT(MONTH FROM CURRENT_DATE) AND A.ANO = EXTRACT(YEAR FROM CURRENT_DATE)),0);
    IF(ID > 0) THEN
    BEGIN
      Exception "..." 'REGISTRO JA VINCULADO AS COTAS DE CENTRO DE CUSTO. NÃO PODE SER INATIVADO!';
    END

    ID = COALESCE((SELECT FIRST 1 A.CODIGO FROM TBCOLABORADOR A WHERE A.CENTRO_DE_CUSTO_CODIGO = OLD.CODIGO AND A.SITUACAO = '1'),0);
    IF(ID > 0) THEN
    BEGIN
      Exception "..." 'REGISTRO JA VINCULADO A COLABORADORES ATIVOS. NÃO PODE SER INATIVADO!';
    END

    IF(CHAR_LENGTH(TRIM(OLD.CODIGO)) = 2)THEN
    BEGIN
       UPDATE TBCENTRO_DE_CUSTO B SET B.STATUS = '0' WHERE SUBSTRING(B.CODIGO FROM 1 FOR 2) = TRIM(OLD.CODIGO) and b.id <> old.id;
    END

    IF(CHAR_LENGTH(TRIM(OLD.CODIGO)) = 5)THEN
    BEGIN
       UPDATE TBCENTRO_DE_CUSTO B SET B.STATUS = '0' WHERE SUBSTRING(B.CODIGO FROM 1 FOR 5) = TRIM(OLD.CODIGO) and b.id <> old.id;
    END

 END


end;

CREATE OR ALTER TRIGGER TTBCENTRO_DE_CUSTO_B03D FOR TBCENTRO_DE_CUSTO
ACTIVE BEFORE DELETE POSITION 2
AS
begin
    IF(CHAR_LENGTH(TRIM(OLD.CODIGO)) = 2)THEN
    BEGIN
       DELETE FROM TBCENTRO_DE_CUSTO B WHERE SUBSTRING(B.CODIGO FROM 1 FOR 2) = TRIM(OLD.CODIGO) AND B.ID <> OLD.ID;
    END

    IF(CHAR_LENGTH(TRIM(OLD.CODIGO)) = 5)THEN
    BEGIN
       DELETE FROM TBCENTRO_DE_CUSTO B WHERE SUBSTRING(B.CODIGO FROM 1 FOR 5) = TRIM(OLD.CODIGO) AND B.ID <> OLD.ID;
    END
end;