-- Schema: wh
-- Stored Procedure: MERGED_PROCEDURE_S151




CREATE procedure [wh].[MERGED_PROCEDURE_S151]
AS
BEGIN

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	declare @DataFineTrim decimal(9, 0)

	select @DataFineTrim = max(dtTrim) from [C6StagingPeriodico].[WSEIAN2]

	create table #WSEIAN (rete varchar(1), CodiceFiscale varchar(20), dtfinval decimal(9, 0))

	--drop table #WSEIAN

	insert into #WSEIAN

		select rete, 'FF@' + CODMAN as CodiceFiscale, dtfinval
		from [C6StagingPeriodico].[WSEIAN2]
		where DTTRIM =  @DataFineTrim
			and isnull(codman, '') <> ''

		union

		select rete, CodFis as CodiceFiscale, dtfinval
		from [C6StagingPeriodico].[WSEIAN2]
		where DTTRIM =  @DataFineTrim
			and isnull(codman, '') = ''

	INSERT into wh.PL_D3_S151ProfiloDiRischio
	SELECT 'C6MartPeriodico.PL_D3_S151ProfiloDiRischio' as ProcedureName, M.rete as i_rete, M.COD_FISCALE as i_codiceFiscale, 	  	 
        M.PROFILO_ASS as codiceProfilo,
		DBO.TOSHORTDATESTRING (M.DATA_INIZIO_VAL) as dataInizioValidita,
		case
			when #WSEIAN.dtfinval <> 0 and #WSEIAN.dtfinval is not null and ltrim(rtrim(#WSEIAN.dtfinval)) <> ''
				then CONVERT(datetime, CONVERT(varchar,CONVERT(int, #WSEIAN.dtfinval)), 0)
			else null
		end as dataScadenzaProfilo,
		CR.MAX_VAR as varMassimo,
		ProfiliDiRischio.NOMEPROFILO as nomeProfilo,
		ProfiliDiRischio.DescrizioneProfilo as descrizioneProfilo,
        m.riskclass,
        m.experience as experince,
		case m.experience
			when 0 then '-'
			when 1 then 'Minima'
			when 2 then 'Bassa'
			when 3 then 'Media'
			when 4 then 'Alta'
			when 5 then 'Molto alta'
			else '-'
		end as descrizioneEsperienza
	FROM
		C6MartPERIODICO.MIFID AS M
		INNER JOIN C6MartPERIODICO.CODIFICA_RISCHIO AS CR
		ON M.PROFILO_ASS = CR.PROFILO
			INNER JOIN DBO.ProfiliDiRischio AS ProfiliDiRischio
			ON M.PROFILO_ASS = ProfiliDiRischio.CODICEPROFILO
				inner join #WSEIAN
				on M.Rete = #WSEIAN.rete
				and M.COD_FISCALE = #WSEIAN.CodiceFiscale
END

