CREATE OR REPLACE TRIGGER LOG_NFCE_INS
BEFORE INSERT
ON LOGNFCE FOR EACH ROW
DECLARE  
  V_NRSEQLOGNFCE VARCHAR2(3);
BEGIN
   BEGIN   
     SELECT NVL(MAX(NRSEQLOGNFCE),0)+1 AS NRSEQLOGNFCE
       INTO V_NRSEQLOGNFCE
       FROM LOGNFCE
      WHERE CDFILIAL   = :NEW.CDFILIAL
        AND CDCAIXA    = :NEW.CDCAIXA
        AND NRSEQVENDA = :NEW.NRSEQVENDA;
   EXCEPTION
   WHEN NO_DATA_FOUND THEN
    V_NRSEQLOGNFCE := '001';
   END;        
   :NEW.NRSEQLOGNFCE := LPAD(V_NRSEQLOGNFCE,3,'0');      
END;

/