CREATE OR REPLACE TRIGGER AtualizaCodigoTributario BEFORE INSERT ON FilaNfe FOR EACH ROW
DECLARE nCount NUMBER;
BEGIN
  select count(*) INTO nCount from NFSAIDACAD nf where nf.numord= :new.numord and TO_NUMBER( TO_CHAR(nf.dtemis, 'YYYY' ) ) > 2012;
    If ( :NEW.SITUACAONFE = 1 or :NEW.SITUACAONFE = 5) AND ( :NEW.TIPONFE = 'S') AND ( nCount > 0) THEN
      BEGIN
        UPDATE itnfsaicad 
               SET ct = (SELECT CASE WHEN LENGTH(RTRIM(NVL(cp.Origem, ' '))) > 0 THEN cp.Origem || SUBSTR(I.ct,2,2) ELSE I.CT END CT
                        FROM itnfsaicad I
                             LEFT JOIN complementoproduto cp ON cp.codpro = I.codpro
                        WHERE I.numord = itnfsaicad.numord
                              AND I.codpro = itnfsaicad.CODPRO)
        WHERE itnfsaicad.numord = :NEW.numord ;
        --
        UPDATE DADOSITEMNFE 
               SET orig = (SELECT CASE WHEN LENGTH(RTRIM(NVL(cp.Origem, ' '))) > 0 THEN cp.Origem ELSE SUBSTR(I.ct,1,1) END ORIG
                           FROM itnfsaicad I
                                LEFT JOIN complementoproduto cp ON cp.codpro = I.codpro
                           WHERE I.NumOrd = DADOSITEMNFE.numord
                                 AND cast(I.item as integer) = DADOSITEMNFE.nitem)
        WHERE DADOSITEMNFE.numord = :NEW.numord ;
      END;
    END IF;
END;