BEGIN
DECLARE
      V_NMRAZSOCFORN VARCHAR2(40);
      V_NRINSJURFORN VARCHAR2(20);
      V_CDFILIAL     VARCHAR2(04);
BEGIN
   FOR C_HISTORICO IN(SELECT CDEMPRESA, NRLANCCONT, NRSEQLANC, CDHISTPADR,
                             RTRIM(SUBSTR(DSHISTLANC, 1, 20)) AS DSHISTLANC,
                             SUBSTR(DSHISTLANC, (LENGTH(DSHISTLANC) - 3),4) AS CDFILIAL
                      FROM LANCCONT
                      WHERE DSHISTLANC LIKE '%FORN:  %' AND
                            CDHISTPADR = '0051')LOOP

      SELECT MAX(F.NMRAZSOCFORN), MAX(F.NRINSJURFORN)
      INTO V_NMRAZSOCFORN, V_NRINSJURFORN
      FROM LANCCONT L, FORNECEDOR F
      WHERE L.CDEMPRESA  = C_HISTORICO.CDEMPRESA  AND
            L.NRLANCCONT = C_HISTORICO.NRLANCCONT AND
            L.NRSEQLANC  = C_HISTORICO.NRSEQLANC  AND
            L.CDCONTCOME = F.CDFORNECED;


      IF (V_NMRAZSOCFORN IS NOT NULL) AND (V_NRINSJURFORN IS NOT NULL) THEN

         SELECT NVL(MAX(CDFILIAL),'')
         INTO V_CDFILIAL
         FROM FILIAL
         WHERE CDFILIAL = C_HISTORICO.CDFILIAL;

         UPDATE LANCCONT
         SET DSHISTLANC = C_HISTORICO.DSHISTLANC||V_NMRAZSOCFORN||' - '||V_NRINSJURFORN||' - '||V_CDFILIAL
         WHERE CDEMPRESA  = C_HISTORICO.CDEMPRESA  AND
                NRLANCCONT = C_HISTORICO.NRLANCCONT;
         COMMIT;
      END IF;
   END LOOP;
END;
END;
/

