CREATE OR ALTER trigger tbnfe_b03i for tbnfe
active before insert position 3
AS
DECLARE VARIABLE CTR_CHAVE_ACESSO_EXISTENTE INTEGER;
BEGIN
    SELECT FIRST 1
        T.CONTROLE
    FROM TBNFE T
    WHERE T.CONTROLE <> NEW.CONTROLE
    AND T.CHAVE_ACESSO = NEW.CHAVE_ACESSO
    AND CHAR_LENGTH(T.CHAVE_ACESSO) = 44
    AND T.NATUREZA = 2
    INTO :CTR_CHAVE_ACESSO_EXISTENTE;

    IF(COALESCE(:CTR_CHAVE_ACESSO_EXISTENTE, 0) > 0) THEN
    BEGIN
        EXCEPTION "..."'DOCUMENTO FISCAL COM A CHAVE DE ACESSO '||TRIM(NEW.CHAVE_ACESSO)|| ' JA GRAVADO NO SISTEMA';
    END
END;