/****** Object:  StoredProcedure [dbo].[P_EST_PROD_BALAN_REPROCESSAR_ULTIMO]    Script Date: 10/07/2012 18:09:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_BALAN_REPROCESSAR_ULTIMO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_PROD_BALAN_REPROCESSAR_ULTIMO]
GO
GO
CREATE PROCEDURE P_EST_PROD_BALAN_REPROCESSAR_ULTIMO AS
DECLARE @CD_EMP INT
DECLARE @CD_FILIAL INT
DECLARE @CD_BALAN INT
DECLARE @CD_USU INT 

set nocount on;
DECLARE RefazerBalanco CURSOR FAST_FORWARD FOR 
SELECT
	CD_EMP,
	CD_FILIAL,
	MAX(CD_BALAN) AS CD_BALAN,
	CD_USU
FROM
	EST_PROD_BALAN
WHERE
	STS_BALAN=2
GROUP BY
	CD_FILIAL,
	CD_USU,
	CD_EMP

OPEN RefazerBalanco
FETCH NEXT FROM RefazerBalanco INTO 
				@CD_EMP,@CD_FILIAL,@CD_BALAN,@CD_USU
	WHILE @@FETCH_STATUS = 0 
		BEGIN	
			PRINT 'Filial.: ' + CONVERT(VARCHAR(20),@CD_FILIAL) + ' Balanco.: ' + CONVERT(VARCHAR(20),@CD_BALAN) 		
			EXEC P_EST_PROD_BALAN_REPROCESSAMENTO @CD_EMP,@CD_FILIAL,@CD_BALAN,@CD_USU

		FETCH NEXT FROM RefazerBalanco INTO 
						@CD_EMP,@CD_FILIAL,@CD_BALAN,@CD_USU
		END
	    CLOSE RefazerBalanco
	    DEALLOCATE RefazerBalanco

