CREATE procedure [C6MartPeriodico].[RP_DM_WSEIAN2]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
exec [dbo].[CreaTabellaBackUp] 'wseian2','C6MartPeriodico'
DECLARE @DataFineTrim VARCHAR(8)  
SET @DataFineTrim = c6martperiodico.getTrimestre2(getDate(),0)
truncate table c6martperiodico.wseian2
INSERT INTO [C6MartPeriodico].[wseian2]
           ([DTTRIM]
           ,[RETE]
           ,[CODFIS]
		   ,[PIVA]
           ,[NOME]
           ,[COGNOME]
           ,[DTNASCI]
           ,[INDIRIZZO]
           ,[CAP]
           ,[CITTA]
           ,[PROVINCIA]
           ,[NAZIONE]
           ,[CODPROF]
           ,[DTINVAL]
           ,[CODMAN]
           ,[CLASSERC]
           ,[COD_PROFEC]
           ,[FLAGPG]
           ,[CLCOMPL]
           ,[FLGCONC]
           ,[FLAGNQP]
           ,[FLGPRLRDE]
           ,[FLGPROF]
           ,[DTFINVAL]
           ,[CONCEMI]
           ,[FREQ]
           ,[LLIQUID]
           ,[PREFSOST]
           ,[FLAGAMB]
           ,[FLAGSOC]
           ,[FLAGGOV]
           ,[ADEGCONC_VALUT]
           ,[SOGLIAESG]
           ,[COERENZA]
           ,[RISERVA]
           ,[INVL_PERIOD]
           ,[MAXCOMPL]
           ,[NOCOMPL]
           ,[SPESA_FORZATA]
           ,[PERC_ILP]
           ,[IMP_RISERVA])
SELECT [DTTRIM]
      ,[RETE]
      ,case when codman<>'' then 'FF@'+codman else [CODFIS] end as CODFIS
	  ,case when LEN(codfis)<16 then codfis else '' end as PIVA
      ,[NOME]
      ,[COGNOME]
      ,[DTNASCI]
      ,[INDIRIZZO]
      ,[CAP]
      ,[CITTA]
      ,[PROVINCIA]
      ,[NAZIONE]
      ,[CODPROF]
      ,[DTINVAL]
      ,[CODMAN]
      ,[CLASSERC]
      ,[COD_PROFEC]
      ,[FLAGPG]
      ,[CLCOMPL]
      ,[FLGCONC]
      ,[FLAGNQP]
      ,[FLGPRLRDE]
      ,[FLGPROF]
      ,[DTFINVAL]
      ,[CONCEMI]
      ,[FREQ]
      ,[LLIQUID]
      ,[PREFSOST]
      ,[FLAGAMB]
      ,[FLAGSOC]
      ,[FLAGGOV]
      ,[ADEGCONC_VALUT]
      ,[SOGLIAESG]
      ,[COERENZA]
      ,[RISERVA]
      ,[INVL_PERIOD]
      ,[MAXCOMPL]
      ,[NOCOMPL]
      ,[SPESA_FORZATA]
      ,[PERC_ILP]
      ,[IMP_RISERVA]
  FROM [C6StagingPeriodico].[WSEIAN2]
 -- where DTTRIM=@DataFineTrim
END