-- Stored procedure
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE procedure [C6MartPeriodico].[DM_RISCHIO_AGGREGATO_OLD2]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @ID_ELAB INT
	DECLARE @TIPO_ELAB VARCHAR(1)
	SET @ID_ELAB = C6MartPeriodico.GETIDELAB()
	SET @TIPO_ELAB = C6MartPeriodico.GETTIPOELAB()
	-- Log esecuzione
	INSERT INTO LOG_ESECUZIONE
		(Nome, Inizio, Nota)
	VALUES (
		'DM_RISCHIO_AGGREGATO',
		GETDATE(),
		'Elaborazione trimestrale'
	)
	TRUNCATE TABLE C6MartPeriodico.RISCHIO_AGGREGATO
	INSERT INTO C6MartPeriodico.RISCHIO_AGGREGATO(
		RETE,
		COD_FISCALE,
		COD_AGGREG,
		VAR_ASSOLUTO_PTF,
		VAR_PERC_PTF,
		CVAR_ASSOLUTO_PTF,
		CVAR_PERC_PTF,
		MCVAR,
		MCVARP,
		BENEFICIO,
		COPERTURA,
		CTV_AGGREG,
		ID_ELAB,
		TIPO_ELAB,
		CREDITRISK,
		Ully_perc,
		CREDITRISKEMIT
	)
	SELECT 
		PROMETEIA_AGGR.RETE AS RETE,
		PROMETEIA_AGGR.CODICEFISCALE AS COD_FISCALE,
		PROMETEIA_AGGR.PORTAFOGLIO AS COD_AGGREG,
		CAST(PROMETEIA_AGGR.VARASSOLUTODIPORTAFOGLIO AS DECIMAL(10,2)) AS VAR_ASSOLUTO_PTF,
		CAST(PROMETEIA_AGGR.VARPERCENTUIALEDIPORTAFOGLIO AS DECIMAL(10,2)) AS VAR_PERC_PTF,
		CAST(PROMETEIA_AGGR.CVARASSOLUTODIPORTAFOGLIO AS DECIMAL(10,2)) AS CVAR_ASSOLUTO_PTF,
		CAST(PROMETEIA_AGGR.CVARPERCENTUALEDIPORTAFOGLIO AS DECIMAL(10,2)) AS CVAR_PERC_PTF,
		CAST(PROMETEIA_AGGR.MCVAR AS DECIMAL(10,2)) AS MCVAR,
		CAST(PROMETEIA_AGGR.MCVARP AS DECIMAL(10,2)) AS MCVARP,
		CAST(PROMETEIA_AGGR.BENEFICIO AS DECIMAL(10,2)) AS BENEFICIO,
		--CAST(PROMETEIA_AGGR.COPERTURA AS DECIMAL(10,2)) AS COPERTURA,
		--V il CC deve avere sempre copertura = 100
		CASE 
			WHEN PORTAFOGLIO = 'COMPLESSIVO|BF|CC' THEN 100
			ELSE CAST(PROMETEIA_AGGR.COPERTURA AS DECIMAL(10,2)) 
		END AS COPERTURA,
		--CAST(PROMETEIA_AGGR.TOTALE AS DECIMAL(15,3)) AS CTV_AGGREG,
		CAST(PROMETEIA_AGGR.TOTALE AS DECIMAL(10,2)) AS CTV_AGGREG,
		@ID_ELAB AS ID_ELAB,
		@TIPO_ELAB AS TIPO_ELAB,
		C6martperiodico.getCreditRiskClass(Ully_perc,numtitrc) AS CREDITRISK,
		CAST(Ully_perc AS DECIMAL(10,2)) AS ULLY_PREC,
		--nuovo
		C6martperiodico.getCreditRiskClassEmit(Ully_perc,numtitrc) as CREDITRISK_EMIT
	FROM 
		C6STAGINGPERIODICO.PROMETEIA_AGGR
--begin transaction
update c6martperiodico.rischio_aggregato
set copertura = 100
where cod_aggreg = 'RISFIN|PIRAMIDE|Liq'
and CTV_AGGREG = 0
--commit
--and cod_fiscale= 'TRPDRA75D15A794T'
	-- Log esecuzione
	UPDATE
		LOG_ESECUZIONE
	SET
		Fine = GETDATE(),
		Tipo = 'INSERT',
		Righe = @@ROWCOUNT
	WHERE
		Nome = 'DM_RISCHIO_AGGREGATO' AND
		Inizio = (
			SELECT
				MAX(Inizio)
			FROM
				LOG_ESECUZIONE
			WHERE
				Nome = 'DM_RISCHIO_AGGREGATO'
		)
END