CREATE procedure [C6MartPeriodico].[DM_DettaglioMovimenti_old]
AS BEGIN
DECLARE @RETE char(1), @CODFIS varchar(16), @CODMAN varchar(6)
DECLARE @DETT_MOV_PREC decimal(15,2), @DETT_MOV_CORR decimal(15,2)
DECLARE @TrimestreDettMov varchar(8)
SET @TrimestreDettMov = C6MartPeriodico.getTrimestreDettMov()
TRUNCATE TABLE C6MartPeriodico.DettaglioMovimenti
DECLARE DettMov_cursor CURSOR FOR
SELECT 
	RETE,
	CODFIS,
	CODMAN
FROM
	[C6StagingPeriodico].[W6APTR]
GROUP BY
	RETE,
	CODFIS,
	CODMAN
/*
SELECT 
	[RETE],
	CASE
		WHEN CODMAN = ''
			THEN CODFIS
			ELSE 'FF@' + CODMAN
		END AS COD_FIS
FROM
	[C6StagingPeriodico].[W6APTR]
GROUP BY
	RETE,
	CASE WHEN CODMAN = '' THEN CODFIS ELSE 'FF@' + CODMAN END
*/
OPEN DettMov_cursor
FETCH NEXT FROM DettMov_cursor
INTO @RETE, @CODFIS, @CODMAN
WHILE @@FETCH_STATUS = 0
BEGIN
	IF EXISTS (SELECT * FROM [C6StagingPeriodico].[S80_EVOL_STAMPA_C6]
	WHERE RETE = @RETE AND COD_FISCALE = @CODFIS)
	BEGIN
		--PRECEDENTE
		SELECT
			@DETT_MOV_PREC = (sum(APPORTI) - sum(PRELIEVI))
			FROM [C6StampeCentralizzate].[C6StagingPeriodico].[W6APTR]
		WHERE
			RETE = @RETE
		AND
			CODFIS = @CODFIS
		AND
			CODMAN = @CODMAN
		AND
			DTTRIM < @TrimestreDettMov
		GROUP BY RETE, CODFIS, CODMAN
		--CORRENTE
		SELECT
			@DETT_MOV_CORR = (sum(APPORTI) - sum(PRELIEVI))
			FROM [C6StampeCentralizzate].[C6StagingPeriodico].[W6APTR]
		WHERE
			RETE = @RETE
		AND
			CODFIS = @CODFIS
		AND
			CODMAN = @CODMAN
		AND
			DTTRIM = @TrimestreDettMov
		GROUP BY RETE, CODFIS, CODMAN
	END
	ELSE
	BEGIN
		--ACCORPAMENTO (cambiare prossima simulazione)
		SELECT
			@DETT_MOV_CORR = (sum(APPORTI) - sum(PRELIEVI))
			FROM [C6StampeCentralizzate].[C6StagingPeriodico].[W6APTR]
		WHERE
			RETE = @RETE
		AND
			CODFIS = @CODFIS
		AND
			CODMAN = @CODMAN
		GROUP BY RETE, CODFIS, CODMAN
	END
	IF @CODMAN <> ''
		SET @CODFIS = 'FF@' + @CODMAN
	INSERT INTO C6MartPeriodico.DettaglioMovimenti
		(RETE, COD_FIS, DETT_MOV_PREC, DETT_MOV_CORR)
	VALUES
		(@RETE, @CODFIS, @DETT_MOV_PREC, @DETT_MOV_CORR)
	SET @DETT_MOV_PREC = null
	SET @DETT_MOV_CORR = null
	FETCH NEXT FROM DettMov_cursor
	INTO @RETE, @CODFIS, @CODMAN
END
CLOSE DettMov_cursor
DEALLOCATE DettMov_cursor
END