/****** Object:  StoredProcedure [dbo].[P_INTEGRACAO_EST_NF_SAI_ALL]    Script Date: 03/12/2014 09:44:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_INTEGRACAO_EST_NF_SAI_ALL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_INTEGRACAO_EST_NF_SAI_ALL]
GO
GO
GO

--Versao 3252
--EXECUTE P_INTEGRACAO_EST_NF_SAI_ALL 01, 2016
CREATE PROCEDURE [dbo].[P_INTEGRACAO_EST_NF_SAI_ALL]( @MES INT=NULL, @ANO INT=NULL,@CD_FILIAL_PAR INT=0 )  AS
 	DECLARE @CD_FILIAL AS INT
	DECLARE @AGORA DATETIME
	
	SET NOCOUNT ON
	IF @ANO IS NULL OR @MES IS NULL
		begin
			SELECT @AGORA=DATEADD(month, -1, GETDATE()), @ANO=YEAR(@AGORA), @MES=MONTH(@AGORA)
		end
	 
	DECLARE cNFSaidaFilial CURSOR FAST_FORWARD READ_ONLY FOR 
	SELECT  
	 	CD_FILIAL
	FROM 
		PRC_FILIAL
	WHERE 
		CD_EMP = 1  
		AND CD_FILIAL = CASE WHEN @CD_FILIAL_PAR = 0 THEN CD_FILIAL ELSE @CD_FILIAL_PAR END
		
	OPEN cNFSaidaFilial
	FETCH NEXT FROM cNFSaidaFilial INTO @CD_FILIAL

	WHILE @@FETCH_STATUS=0
	BEGIN
		  
		PRINT 'Filial ' + CONVERT(VARCHAR, @CD_FILIAL) 
		 
		UPDATE
			EST_NF_SAI
		SET
			EMAIL_TRANSP=EMAIL_TRANSP + ' ',
			CD_USU = 1
		WHERE
			CD_EMP =1
			AND CD_FILIAL = @CD_FILIAL 
			AND MONTH(DT_EMI_NF)=@MES
			AND YEAR(DT_EMI_NF)=@ANO
		FETCH NEXT FROM  cNFSaidaFilial INTO @CD_FILIAL 
	END
	
CLOSE cNFSaidaFilial
DEALLOCATE cNFSaidaFilial

GO


