/****** Object:  StoredProcedure [dbo].[P_CORRIGE_EST_NF_ENT_IT_PERC_DESC]    Script Date: 05/20/2013 17:10:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_CORRIGE_EST_NF_ENT_IT_PERC_DESC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_CORRIGE_EST_NF_ENT_IT_PERC_DESC]
GO
GO
GO
CREATE PROCEDURE P_CORRIGE_EST_NF_ENT_IT_PERC_DESC AS

	SET NOCOUNT ON
	DECLARE @CD_NF INT, @CD_FILIAL INT

	DECLARE cNF CURSOR FAST_FORWARD FOR 
	select  DISTINCT
		EST_NF_ENT.CD_NF,
		EST_NF_ENT.CD_FILIAL 
	from
		EST_NF_ENT 
		INNER JOIN EST_NF_ENT_IT ON
		EST_NF_ENT.CD_EMP = EST_NF_ENT_IT.CD_EMP AND
		EST_NF_ENT.CD_FILIAL = EST_NF_ENT_IT.CD_FILIAL AND
		EST_NF_ENT.CD_NF = EST_NF_ENT_IT.CD_NF 
	WHERE       
		EST_NF_ENT.CD_EMP = 1
		AND EST_NF_ENT_IT.PERC_DESC > 100 
		AND EST_NF_ENT.DT_ENT > CONVERT(CHAR(10),GETDATE()- 160,112);
	 
	OPEN cNF
	FETCH NEXT FROM cNF INTO @CD_NF, @CD_FILIAL;


	WHILE @@FETCH_STATUS=0
	  begin
		
		print 'Filial ' + convert(varchar,@cd_FILIAL) +  ' ... atualizando CD_NF  ' + convert(varchar,@cd_nf) ;
		UPDATE
		   EST_NF_ENT_IT
		SET
			EST_NF_ENT_IT.PERC_DESC = ((EST_NF_ENT_IT.VLR_DESC / EST_NF_ENT_IT.QT_IT) / EST_NF_ENT_IT.VLR_IT) * 100.
		FROM        
			EST_NF_ENT_IT  
		WHERE       
			EST_NF_ENT_IT.CD_EMP = 1
			AND EST_NF_ENT_IT.CD_NF=@CD_NF
			AND EST_NF_ENT_IT.PERC_DESC > 100 
			AND EST_NF_ENT_IT.CD_FILIAL =@CD_FILIAL; 

		FETCH NEXT FROM cNF INTO @CD_NF, @CD_FILIAL;
	  end
	   
	CLOSE cNF
	DEALLOCATE cNF




