SET TERM ^ ;

CREATE OR ALTER trigger ttbmodelo_cor_b0d for tbmodelo_cor
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE EXISTE_GRUPO INTEGER;
begin
       :EXISTE_GRUPO = (SELECT FIRST 1
                            IIF(M.GRUPO_PRODUTO_ID > 0, 1, 0)
                        FROM TBMODELO M
                        WHERE M.CODIGO = OLD.MODELO_ID);

       IF(:EXISTE_GRUPO = 0) THEN
       BEGIN
           DELETE FROM TBPRODUTO WHERE MODELO_CODIGO = OLD.MODELO_ID AND COR_CODIGO = OLD.COR_ID;
       END

       HISTORICO = 'Cor: '||OLD.COR_ID||'-'||Coalesce((Select First 1 C.descricao From TbCor C Where C.Codigo = Old.Cor_Id),'')||' excluída.';

       INSERT INTO TBHISTORICO (
       TABELA, TABELA_ID, USUARIO, IP, HISTORICO) VALUES (
      'TBMODELO', OLD.MODELO_ID,
      (Select First 1 MON$USER from mon$attachments where mon$attachment_id = current_connection),
      (Select First 1 MON$REMOTE_ADDRESS from mon$attachments where mon$attachment_id = current_connection),
       :Historico);
end
^

SET TERM ; ^

