--Criando a tabela temporaria
CREATE TABLE #RsPdv (	
					CD_CTR INT IDENTITY (1, 1),
					CD_EMP INT,
					CD_FILIAL INT,
					CD_CTR_CUPOM INT,
					CD_CX INT,
					DT_CUPOM DATETIME,
					NR_COO INT)
				
INSERT INTO #RsPdv
SELECT 
	A.CD_EMP,
	A.CD_FILIAL,
	A.CD_CTR,
	A.CD_CX,
	A.DT_CUPOM,
	A.NR_COO
FROM 
	PDV_CUPOM_NAO_FISCAL A INNER JOIN (
select 
	CD_EMP,
	CD_FILIAL,
	CD_CX,
	DT_CUPOM,
	NR_COO
	from	
		PDV_CUPOM_NAO_FISCAL
GROUP BY 	
	CD_EMP,
	CD_FILIAL,
	CD_CX,
	DT_CUPOM,
	NR_COO
HAVING COUNT(1)> 1) T ON 
	A.CD_EMP = T.CD_EMP AND
	A.CD_FILIAL = T.CD_FILIAL AND
	A.CD_CX = T.CD_CX AND
	A.NR_COO= T.NR_COO AND
	A.DT_CUPOM=T.DT_CUPOM 
GROUP BY 
	A.CD_EMP,
	A.CD_FILIAL,
	A.CD_CTR,
	A.CD_CX,
	A.DT_CUPOM,
	A.NR_COO
order by
	A.DT_CUPOM,
	A.NR_COO

DECLARE @CD_CTR INT
DECLARE @CD_FILIAL int
DECLARE @CD_EMP INT
DECLARE @NR_COO INT
DECLARE @CD_CTR_CUPOM INT 

SET NOCOUNT ON
DECLARE VendasNaoFiscal CURSOR FAST_FORWARD FOR
		SELECT 
			CD_CTR,
			CD_CTR_CUPOM,
			CD_EMP,
			CD_FILIAL,
			NR_COO
		FROM 
			#RsPdv A

OPEN VendasNaoFiscal
FETCH NEXT FROM VendasNaoFiscal INTO @CD_CTR,@CD_CTR_CUPOM,@CD_EMP,@CD_FILIAL,@NR_COO

WHILE @@FETCH_STATUS=0
	Begin	
		begin
			UPDATE 
				PDV_CUPOM_NAO_FISCAL
			SET
				NR_COO = NR_COO + @CD_CTR
			WHERE
				CD_EMP	  = @CD_EMP
				AND CD_FILIAL = @CD_FILIAL
				AND CD_CTR = @CD_CTR_CUPOM
			
		end
		FETCH NEXT FROM VendasNaoFiscal INTO @CD_CTR,@CD_CTR_CUPOM,@CD_EMP,@CD_FILIAL,@NR_COO
	End
PRINT 'Concluido.'
CLOSE VendasNaoFiscal;
DEALLOCATE VendasNaoFiscal;
DROP TABLE #RsPdv;

IF EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IX_PDV_CUPOM_NAO_FISCAL_NR_CUPOM')
	DROP INDEX IX_PDV_CUPOM_NAO_FISCAL_NR_CUPOM ON [dbo].[PDV_CUPOM_NAO_FISCAL]

GO

/****** Object:  Index [IX_PDV_CUPOM_NAO_FISCAL_NR_CUPOM]    Script Date: 14/11/2014 16:35:18 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_PDV_CUPOM_NAO_FISCAL_NR_CUPOM] ON [dbo].[PDV_CUPOM_NAO_FISCAL]
(
	[CD_EMP] ASC,
	[CD_FILIAL] ASC,
	[CD_CX] ASC,
	[DT_CUPOM] ASC,
	[NR_COO] ASC
)
INCLUDE ( 	[CD_CTR]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
GO


