SET TERM ^ ;

CREATE OR ALTER trigger ttbnfe_b04i for tbnfe
active before insert position 4
AS
DECLARE VARIABLE NUMERO_NOTAFISCAL INTEGER;
DECLARE VARIABLE DESC_DOC VARCHAR(200);
BEGIN
    IF(COALESCE(NEW.PDV_DEVOLUCAO_ID, 0) > 0) THEN
    BEGIN
        FOR SELECT FIRST 1
            T.NUMERO_NOTAFISCAL,
            FN_LPAD(T.NUMERO_NOTAFISCAL, 9, '0')||'/'||T.SERIE AS DESC_DOC
        FROM TBNFE T
        WHERE
            T.PDV_DEVOLUCAO_ID  = NEW.PDV_DEVOLUCAO_ID
        AND T.CONTROLE          <> NEW.CONTROLE
        INTO :NUMERO_NOTAFISCAL, :DESC_DOC
        DO BEGIN
            IF(:NUMERO_NOTAFISCAL > 0) THEN
            BEGIN
                EXCEPTION "..."'DEVOLUCAO JA VINCULADA NO DOCUMENTO FISCAL DE ENTRADA '||:DESC_DOC||'. OPERACAO CANCELADA.';
            END
        END
    END
END
^

SET TERM ; ^

