 
IF EXISTS (SELECT *FROM SYS.PROCEDURES WHERE NAME= 'P_ATUALIZA_PDV_CX_EST_NF_SERIE')
BEGIN
      DROP PROCEDURE  P_ATUALIZA_PDV_CX_EST_NF_SERIE 
END ;
GO 
-- EXEC P_ATUALIZA_PDV_CX_EST_NF_SERIE
CREATE PROCEDURE P_ATUALIZA_PDV_CX_EST_NF_SERIE 

AS 
DECLARE @CD_FILIAL    INT ;
DECLARE @CD_CTR       INT ;
DECLARE @CD_NF_SERIE  INT ;
DECLARE @NR_ULT       INT ;
DECLARE @CD_CX        INT ;

DECLARE C1 CURSOR 
FOR 
	  SELECT A.CD_FILIAL 
	        ,A.CD_CTR
	        ,A.CD_NF_SERIE
	        ,A.NR_ULT 
	        ,B.CD_CX
	    FROM PDV_CX_EST_NF_SERIE A
	         INNER  JOIN PDV_CX B ON A.CD_CTR  = B.CD_CTR_SERIE 
						 INNER  JOIN EST_NF_SERIE C ON C.CD_NF_SERIE = A.CD_NF_SERIE	       
	   WHERE A.CD_EMP =1
	 

OPEN C1;
FETCH NEXT FROM C1 INTO @CD_FILIAL,@CD_CTR,@CD_NF_SERIE,@NR_ULT,@CD_CX
WHILE @@FETCH_STATUS = 0 

BEGIN 

DECLARE @NR_ULT_MAIOR INT
     SET @NR_ULT_MAIOR = (SELECT  
								 MAX(NR_ECF) NR_ECF
						    FROM PDV_VD 
						   WHERE CD_FILIAL = @CD_FILIAL 
						     AND CD_EMP    = 1 
						     AND CD_CX     = @CD_CX
							 AND DT_VD     >= GETDATE() - 15
						   GROUP BY CD_FILIAL
						           ,CD_CX
						   )
						    
		 UPDATE A
		    SET A.NR_ULT = @NR_ULT_MAIOR,
			    A.DT_ALT = GETDATE()
				
		   FROM PDV_CX_EST_NF_SERIE A 
		 	    INNER  JOIN PDV_CX B ON A.CD_CTR  = B.CD_CTR_SERIE 
		 	             	INNER  JOIN EST_NF_SERIE C ON C.CD_NF_SERIE = A.CD_NF_SERIE	       
		  WHERE A.CD_FILIAL    = @CD_FILIAL
		    AND A.CD_CTR       = @CD_CTR
		    AND A.CD_NF_SERIE  = @CD_NF_SERIE
		    AND B.CD_CX		   = @CD_CX
		    AND A.NR_ULT 	   < @NR_ULT_MAIOR
		 
FETCH NEXT FROM C1 INTO @CD_FILIAL,@CD_CTR,@CD_NF_SERIE,@NR_ULT,@CD_CX

END
CLOSE C1;
DEALLOCATE C1;