﻿-- [dbo].[SP_PDF_CANCELLASTORICIZZATO] 'M'
 CREATE PROCEDURE [dbo].[SP_PDF_CANCELLASTORICIZZATO]
	@idProvenienza varchar(1) 
AS  
BEGIN
 BEGIN TRANSACTION
declare @ris as varchar(max)
 SET @ris = ''
declare @dtstamp as datetime
set @dtstamp = GETDATE()
--**************************************************************************************
 SELECT p.IdPdf INTO #CANCELLATILOGICA FROM DocumentiPdf p  inner join  ImagePdf i on p.idPdf = i.idPdf
 WHERE p.idStato = 'E' 
	AND p.idArchivio = 'O' 
	AND DATEDIFF(day,p.dtEliminato,GETDATE()) > 30	 
	AND i.[image] is not null
  SET @ris =   'di  ' +  convert(varchar,@@ROWCOUNT)  + ' ' +  @ris
 UPDATE ImagePdf SET [image] = NULL WHERE idPdf in (SELECT idPdf FROM #CANCELLATILOGICA)
  SET @ris =   'CANCELLATILOGICA [IMAGENULL =  ' +  convert(varchar,@@ROWCOUNT)  + '] ' +  @ris
 INSERT INTO LogPdf 
 	SELECT idPdf,@dtstamp,4,@idProvenienza from #CANCELLATILOGICA
 --**************************************************************************************
 SELECT p.IdPdf  INTO #PROVISORIVECCHI FROM DocumentiPdf p  inner join  ImagePdf i on p.idPdf = i.idPdf
 WHERE p.idStato = 'P' 
	AND p.idArchivio = 'O' 
	AND DATEDIFF(day,p.dtCreazione,GETDATE()) > 180	 
	AND i.[image] is not null	
 SET @ris =   'di  ' +  convert(varchar,@@ROWCOUNT)  + ' ' +  @ris
 UPDATE ImagePdf SET [image] = NULL WHERE idPdf in (SELECT idPdf FROM #PROVISORIVECCHI)
  SET @ris =   'IMAGENULL =  ' +  convert(varchar,@@ROWCOUNT)  + '] ' +  @ris
 UPDATE DocumentiPdf SET idStato = 'E'     
    FROM  DocumentiPdf p INNER JOIN #PROVISORIVECCHI t ON p.idPdf = t.idPdf
   SET @ris =   'PROVSORIVECCHI [STATOE =  ' +  convert(varchar,@@ROWCOUNT)  + ' ' +  @ris
 INSERT INTO LogPdf 
  	SELECT idPdf,@dtstamp,5,@idProvenienza from #PROVISORIVECCHI 
--**************************************************************************************
 SELECT p.IdPdf INTO #RESTORATIVECCHI FROM DocumentiPdf p  inner join  ImagePdf i on p.idPdf = i.idPdf
 WHERE p.idStato = 'D' 
	AND p.idArchivio = 'R' 
	AND DATEDIFF(day,ISNULL(p.dtRestore,GETDATE()),GETDATE())> 30	 
	AND i.[image] is not null	
  SET @ris =   'di  ' +  convert(varchar,@@ROWCOUNT)  + ' ' +  @ris 
  --UPDATE ImagePdf SET [image] = NULL  WHERE idPdf in (SELECT idPdf FROM #RESTORATIVECCHI)
  SET @ris =   'IMAGENULL =  ' +  convert(varchar,@@ROWCOUNT)  + '] ' +  @ris
 UPDATE DocumentiPdf SET idArchivio = 'A',dtRestore = null WHERE idPdf in (SELECT idPdf FROM #RESTORATIVECCHI)
  SET @ris =   'RESTORATIVECCHI [STATOA =  ' +  convert(varchar,@@ROWCOUNT)  + ' ' +  @ris
 INSERT INTO LogPdf 
 	SELECT idPdf,@dtstamp,6,@idProvenienza from #RESTORATIVECCHI 
--**************************************************************************************
 COMMIT TRANSACTION	  
 select @ris
END