IF NOT OBJECT_ID('P_EST_PROD_CPL_TRIB_ST_CRED') IS NULL
	BEGIN 
		DROP PROCEDURE P_EST_PROD_CPL_TRIB_ST_CRED
	END

GO

CREATE PROCEDURE  P_EST_PROD_CPL_TRIB_ST_CRED (@CD_EMP INT, @CD_FILIAL INT, @CD_PROD INT, @QT_IT_VD MONEY)

AS					
BEGIN

DECLARE @QT_IT_REG MONEY 

DECLARE @RS_CD_CTR				int
DECLARE @RS_CD_EMP				int
DECLARE @RS_CD_FILIAL			int
DECLARE @RS_CD_PROD				int
DECLARE @RS_DT_MOV				datetime
DECLARE @RS_QT_IT				money	
DECLARE @RS_QT_IT_SLD			money						
DECLARE @RS_VLR_BASE_ICMS		money
DECLARE @RS_VLR_ICMS			money
DECLARE @RS_ALIQ_ICMS			money
DECLARE @RS_VLR_BASE_ICMS_ST	money
DECLARE @RS_VLR_ICMS_ST			money
						

 

DECLARE @TBL_RET TABLE (CD_CTR				int,
						CD_EMP				int,
						CD_FILIAL			int,
						CD_PROD				int,
						DT_MOV				datetime,
						QT_IT				money,						
						VLR_BASE_ICMS		money,
						VLR_ICMS			money,
						ALIQ_ICMS			money,
						VLR_BASE_ICMS_ST	money,
						VLR_ICMS_ST			money)


DECLARE RS_RESULT
	CURSOR FOR 	
		SELECT 
			CD_CTR,
			CD_EMP,
			CD_FILIAL,
			CD_PROD,
			DT_MOV,
			QT_IT,
			QT_IT_SLD,
			VLR_BASE_ICMS,
			VLR_ICMS,
			ALIQ_ICMS,
			VLR_BASE_ICMS_ST,
			VLR_ICMS_ST			
		FROM EST_PROD_CPL_TRIB_ST_CRED 
		WHERE 
			CD_EMP			= @CD_EMP
			AND CD_FILIAL	= @CD_FILIAL
			AND CD_PROD		= @CD_PROD
			AND QT_IT_SLD	> 0
		ORDER BY DT_MOV
									
		--Abrindo cursor
		OPEN RS_RESULT
		
		--Atribuindo valores do select nas variáveis
		FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_CTR,
				@RS_CD_EMP,
				@RS_CD_FILIAL,
				@RS_CD_PROD,
				@RS_DT_MOV,
				@RS_QT_IT,
				@RS_QT_IT_SLD,
				@RS_VLR_BASE_ICMS,
				@RS_VLR_ICMS,
				@RS_ALIQ_ICMS,
				@RS_VLR_BASE_ICMS_ST,
				@RS_VLR_ICMS_ST
					 

		--Iniciando laço
		WHILE @@FETCH_STATUS = 0
			BEGIN							
				IF @QT_IT_VD > @RS_QT_IT_SLD
					BEGIN
						SET @QT_IT_REG	= @RS_QT_IT_SLD
						SET @QT_IT_VD	= @QT_IT_VD - @RS_QT_IT_SLD
					END
				ELSE
					BEGIN
						SET @QT_IT_REG	= @QT_IT_VD
						SET @QT_IT_VD	= 0
					END
				
				INSERT INTO @TBL_RET (CD_CTR, CD_EMP, CD_FILIAL, CD_PROD, DT_MOV, QT_IT,  
									  VLR_BASE_ICMS, VLR_ICMS, ALIQ_ICMS, VLR_BASE_ICMS_ST, VLR_ICMS_ST)
									  
							  VALUES (@RS_CD_CTR, @RS_CD_EMP, @RS_CD_FILIAL, @RS_CD_PROD, @RS_DT_MOV, @QT_IT_REG,  
									  @RS_VLR_BASE_ICMS, @RS_VLR_ICMS, @RS_ALIQ_ICMS, @RS_VLR_BASE_ICMS_ST, @RS_VLR_ICMS_ST)
			
				IF @QT_IT_VD <= 0
					BEGIN 
						BREAK
					END	
				
				--Atribuindo valores do select nas variáveis
				FETCH NEXT FROM RS_RESULT INTO 
						@RS_CD_CTR,
						@RS_CD_EMP,
						@RS_CD_FILIAL,
						@RS_CD_PROD,
						@RS_DT_MOV,
						@RS_QT_IT,
						@RS_QT_IT_SLD,
						@RS_VLR_BASE_ICMS,
						@RS_VLR_ICMS,
						@RS_ALIQ_ICMS,
						@RS_VLR_BASE_ICMS_ST,
						@RS_VLR_ICMS_ST			
			END

	CLOSE RS_RESULT
	DEALLOCATE RS_RESULT			
	
	SELECT * FROM @TBL_RET	
	RETURN
	

END






