ALTER TABLE GRUPPROD  ADD IDMSGATUEST        VARCHAR2(1)            DEFAULT '0' NOT NULL
        CONSTRAINT CKC_GRUPPROD_IDMSGATUEST CHECK (IDMSGATUEST IN ('0','1','2'))
/

ALTER TABLE GRUPPROD  ADD IDIMPPRODEST        VARCHAR2(1)            DEFAULT 'N' NOT NULL
        CONSTRAINT CKC_GRUPPROD_IDIMPPRODEST CHECK (IDIMPPRODEST IN ('S','N'))
/

ALTER TABLE LANCTOESTOQ ADD CDGRUPPRODLCEST   VARCHAR2(10)           NULL
/

ALTER TABLE LANCTOESTOQ
    ADD CONSTRAINT FKEST00629_CDGRUPPRODLCEST FOREIGN KEY  (CDGRUPPRODLCEST)
       REFERENCES GRUPPROD (CDGRUPPROD)
/

DECLARE
   V_CDGRUPPROD  VARCHAR2(10);
BEGIN
   BEGIN
      SELECT MAX(CDGRUPPROD)
        INTO V_CDGRUPPROD
        FROM GRUPPROD;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDGRUPPROD := NULL;
   END;

   IF NOT V_CDGRUPPROD IS NULL THEN
      FOR C_FILIAIS IN (SELECT CDFILIAL FROM FILIAL)
      LOOP
         FOR C_ITLANCTOEST IN (SELECT DISTINCT CDFILIAL, NRLANCESTQ
                                 FROM ITLANCTOEST
                                WHERE CDFILIMOVI = C_FILIAIS.CDFILIAL
                                  AND IDTIPOMOVI = '1'
                                  AND IDAJUSTEIMPORT = 'S')
         LOOP
            UPDATE LANCTOESTOQ
               SET CDGRUPPRODLCEST = V_CDGRUPPROD
             WHERE CDFILIAL   = C_ITLANCTOEST.CDFILIAL
               AND NRLANCESTQ = C_ITLANCTOEST.NRLANCESTQ;
         END LOOP;
         COMMIT;
      END LOOP;
   END IF;
END;
/