CREATE procedure [C6MartPeriodico].[RP_DM_WSEIRPF]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE @DataFineTrim VARCHAR(8)  
SET @DataFineTrim = c6martperiodico.getTrimestre2(getDate(),0)
  SELECT 
   rpf.[dttrim]
  ,rpf.[rete]
  ,case when rpf.codman <>'' then 'FF@'+rpf.codman else rpf.codfis end as chiave_acn
  ,rpf.[codfis]
  ,rpf.[codman]
  ,rpf.[flgprof]
  ,rpf.[flgec]
  ,rpf.[data_ora_refresh]
  ,rpf.[data_ora_inse]
  ,rpf.[data_ora_aggi]
  into #WSEIRPF_temp
  FROM [C6StagingPeriodico].[WSEIRPF] rpf
  where rpf.flgprof in ('P','S') and rpf.dttrim=@DataFineTrim
  SELECT 
   rpf.[dttrim]
  ,rpf.[rete]
  ,rpf.chiave_acn
  ,rpf.[codfis]
  ,rpf.[codman]
  ,rpf.[flgprof]
  ,rpf.[flgec]
  ,rpf.[data_ora_refresh]
  ,rpf.[data_ora_inse]
  ,rpf.[data_ora_aggi]
  ,case when ac.TIP_CONTRATTO=3 then 'S' else 'N' end as isDirect
  into #WSEIRPF
  from #WSEIRPF_temp rpf
  inner join C6StagingPeriodico.APPO_CONTRATTI AC
  on rpf.rete=AC.rete and rpf.chiave_acn=AC.COD_FISCALE
    SELECT 
   rpf.[dttrim]
  ,rpf.[rete]
  ,rpf.chiave_acn
  ,rpf.[codfis]
  ,rpf.[codman]
  ,rpf.[flgprof]
  ,rpf.[flgec]
  ,rpf.[data_ora_refresh]
  ,rpf.[data_ora_inse]
  ,rpf.[data_ora_aggi]
  ,rpf.isDirect
  into #WSEI
  FROM #WSEIRPF rpf
   inner join C6MartPeriodico.wseian2 an2 on rpf.rete+rpf.chiave_acn=an2.rete+an2.codfis
  where rpf.flgprof='P' and rpf.dttrim=@DataFineTrim and CODPROF='0' and isDirect='N'
  union all 
  SELECT 
   rpf.[dttrim]
  ,rpf.[rete]
  ,rpf.chiave_acn
  ,rpf.[codfis]
  ,rpf.[codman]
  ,rpf.[flgprof]
  ,rpf.[flgec]
  ,rpf.[data_ora_refresh]
  ,rpf.[data_ora_inse]
  ,rpf.[data_ora_aggi]
  ,rpf.isDirect
  FROM #WSEIRPF rpf
   inner join C6MartPeriodico.wseian2 an2 on rpf.rete+rpf.chiave_acn=an2.rete+an2.codfis
   inner join C6MartPeriodico.vPatrimonioBFAggregato patr on patr.rete=rpf.rete and patr.cod_fiscale=rpf.chiave_acn
  where rpf.flgprof='P' and rpf.dttrim=@DataFineTrim and CODPROF='0' and isDirect='S' and ctv>=100000
truncate table c6martperiodico.wseirpf
INSERT INTO [C6MartPeriodico].[wseirpf](
            [dttrim]
		   ,[rete]
		   ,[chiave_acn]
		   ,[codfis]
		   ,[codman]
		   ,[flgprof]
		   ,[flgec]
		   ,[data_ora_refresh]
		   ,[data_ora_inse]
		   ,[data_ora_aggi])  
  SELECT 
   ws.[dttrim]
  ,ws.[rete]
  ,WS.chiave_acn
  ,ws.[codfis]
  ,ws.[codman]
  ,ws.[flgprof]
  ,ws.[flgec]
  ,ws.[data_ora_refresh]
  ,ws.[data_ora_inse]
  ,ws.[data_ora_aggi]
  FROM #WSEI WS
  inner join C6StagingPeriodico.APPO_CONTRATTI AC
  on WS.rete=AC.rete and WS.chiave_acn=AC.COD_FISCALE
  drop table if exists #WSEIRPF
    drop table if exists #WSEI
END