create PROCEDURE [C6MartPeriodico].[DM_DettaglioMovimenti_old2]
AS BEGIN
--nuovo
DECLARE @MaxTrim varchar(8)
DECLARE @MinTrim varchar(8)
--fine nuovo
/*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
SELECT @MaxTrim = max(DTTRIM) FROM
(SELECT TOP 2 DTTRIM from [C6StagingPeriodico].[W6APAG]
ORDER BY DTTRIM DESC) a
SELECT @MinTrim = min(DTTRIM) FROM
(SELECT TOP 2 DTTRIM from [C6StagingPeriodico].[W6APAG]
ORDER BY DTTRIM DESC) b
--SELECT * FROM C6MartPeriodico.DettaglioMovimenti
--SELECT * FROM [C6StagingPeriodico].[W6APAG]
INSERT INTO C6MartPeriodico.DettaglioMovimenti
SELECT 
	RETE,
	CASE
		WHEN CODMAN  = '' --is null
			THEN CODFIS
			ELSE 'FF@' + CODMAN
		END AS COD_FIS,
	(APPORTI - PRELIEVI) AS DETT_MOV,
	1
FROM
	[C6StagingPeriodico].[W6APAG]
WHERE
	DTTRIM = @MaxTrim
INSERT INTO C6MartPeriodico.DettaglioMovimenti
SELECT 
	RETE,
	CASE
		WHEN CODMAN = '' --is null
			THEN CODFIS
			ELSE 'FF@' + CODMAN
		END AS COD_FIS,
	(APPORTI - PRELIEVI) AS DETT_MOV,
	0
FROM
	[C6StagingPeriodico].[W6APAG]
WHERE
	DTTRIM = @MinTrim
END