﻿-- =============================================
-- Author:		Atzeri Emanuele
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--select * from c6mart.vcontratti
--where cod_fiscale = 'VNCLDA54H15M109X'
--------------------------------------------
--insert into ReportDaCancellare
--------------------------------------------
--select rete, codicefiscale, SUBSTRING(NomeFile, 1, 11), idreport, datagenerazione
--from c6mart.gestione_pdf_ftp
--where SUBSTRING(NomeFile, 1, 11) = '010580CO200'
CREATE PROCEDURE [dbo].[SRV_ReportDaCancellare]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	--SET NOCOUNT ON;
BEGIN TRANSACTION
	BEGIN TRY
		update c6mart.contrattosei_metadati
		set invioBenvenuto = 'N'
		from c6mart.contrattosei_metadati m
		join c6mart.vcontratti v
		on m.chiaveClientepb = v.chiaveclientepb
		join c6mart.gestione_pdf_ftp p
		on v.cod_fiscale = p.codiceFiscale
		and v.rete = p.rete
		where p.idreport in
		(
			select idreport from ReportDaCancellare
		)
		delete from c6mart.gestione_pdf_ftp where idreport in
		(
			select idreport from ReportDaCancellare
		)
		insert into ReportDaCancellareBCK
		(rete, codfis, codconf, idreport, dtgenera)
		select * from ReportDaCancellare
		truncate table ReportDaCancellare
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
	DECLARE @Msg NVARCHAR(MAX)  
	SELECT @Msg=ERROR_MESSAGE() 
	RAISERROR('Descrizione errore: %s', 20, 101,@msg) WITH LOG
END CATCH
END