ALTER TABLE CLIENTE ADD CDFILTABPREC VARCHAR(4)
GO
ALTER TABLE CLIENTE ADD CDTABEPREC VARCHAR(3)
GO
DECLARE @V_CDTABPREC   VARCHAR(3);
DECLARE @V_DTFINVGPREC DATETIME;
DECLARE @V_DTREAJUSTE  DATETIME;
DECLARE @V_VRREAJUSTE  NUMERIC;

DECLARE @C_CDFILIAL    VARCHAR(4);
DECLARE @C_CDTABEPREC  VARCHAR(3);
DECLARE @C_DTINIVGPREC DATETIME;
DECLARE @C_CDCLIENTE   VARCHAR(21);
 
BEGIN
   DECLARE CUR_TABELA CURSOR FOR
      SELECT DISTINCT I.CDFILIAL, I.CDTABEPREC, I.DTINIVGPREC, I.CDCLIENTE
      FROM ITEMPRECOCLI I, TABEVEND T
      WHERE GETDATE() BETWEEN T.DTINIVGPREC AND T.DTFINVGPREC AND
            T.CDFILIAL    = I.CDFILIAL   AND
            T.CDTABEPREC  = I.CDTABEPREC AND
            T.DTINIVGPREC = I.DTINIVGPREC

   OPEN CUR_TABELA;
   FETCH NEXT FROM CUR_TABELA INTO @C_CDFILIAL, @C_CDTABEPREC, @C_DTINIVGPREC, @C_CDCLIENTE;

   WHILE (@@FETCH_STATUS = 0) BEGIN

      SELECT @V_CDTABPREC = MAX(CDTABEPREC)
      FROM TABEVEND
      WHERE CDFILIAL = @C_CDFILIAL;

      SET @V_CDTABPREC = RIGHT(REPLICATE('0',3) + RTRIM(CAST((CAST(@V_CDTABPREC AS INT) + 1) AS CHAR(3))),3)

      /*insere a tabela*/
      INSERT INTO TABEPREC
         (CDFILIAL, CDTABEPREC, NMTABEPREC)
      VALUES
         (@C_CDFILIAL, @V_CDTABPREC, 'Tabela cliente');

      SELECT @V_DTFINVGPREC = DTFINVGPREC, @V_DTREAJUSTE = DTREAJUSTE,
             @V_VRREAJUSTE = VRREAJUSTE
      FROM TABEVEND
      WHERE CDFILIAL    = @C_CDFILIAL AND
            CDTABEPREC  = @C_CDTABEPREC AND
            DTINIVGPREC = @C_DTINIVGPREC;

      INSERT INTO TABEVEND
         (CDFILIAL, CDTABEPREC, DTINIVGPREC, DTFINVGPREC,
          DTREAJUSTE, VRREAJUSTE)
      VALUES
         (@C_CDFILIAL, @V_CDTABPREC, @C_DTINIVGPREC, @V_DTFINVGPREC,
          @V_DTREAJUSTE, @V_VRREAJUSTE);

      /*insere os produtos*/
      INSERT INTO ITEMPRECO
         (CDFILIAL, CDTABEPREC, DTINIVGPREC, CDPRODUTO, CDPRPAITABPR,
          VRPRECITEM, VRPRECITEMCL, VRPRECMAXITE, IDPRECVARIA,
          VRPRESUGITEM, VRCUSTITEM, VRMKUPITEM)
      (SELECT CDFILIAL, @V_CDTABPREC, @C_DTINIVGPREC, CDPRODUTO, CDPRPAITABPR,
              VRPRCLITEM, VRPRCLITEMCL, VRPRMAXCLITE, 'N',
              0, VRCUSTITEMCL, VRMKUPITEMCL
       FROM ITEMPRECOCLI
       WHERE CDFILIAL    = @C_CDFILIAL    AND
             CDTABEPREC  = @C_CDTABEPREC  AND
             DTINIVGPREC = @C_DTINIVGPREC AND
             CDCLIENTE   = @C_CDCLIENTE);

       /*Updata a tabela cadastrada no cliente*/
       UPDATE CLIENTE
       SET CDFILTABPREC = @C_CDFILIAL,
           CDTABEPREC   = @V_CDTABPREC
       WHERE CDCLIENTE = @C_CDCLIENTE;

   FETCH NEXT FROM CUR_TABELA INTO @C_CDFILIAL, @C_CDTABEPREC, @C_DTINIVGPREC, @C_CDCLIENTE;
   END;
   CLOSE CUR_TABELA;
   DEALLOCATE CUR_TABELA;
END;
GO