-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[UtilEliminaReportAgenteCliente]
	-- Add the parameters for the stored procedure here
	@ReteAgente varchar(7),
	@CodFiscCliente  varchar(16)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT OFF;
--cancellazione tabelle dei report del cliente
--delete ReportSezionePers
	BEGIN TRAN
	PRINT 'DELETING reportSezionePers 1.....'
delete from reportSezionePers
	from 
		reportSezionePers rsp
	inner join Report r
	on 
		rsp.idreport = r.idReport
	inner join reportpercliente rc
	on 
		rc.idReport = r.idReport
	inner join cliente c
	on 
		c.idcliente = rc.idcliente
	where c.utente = @ReteAgente
		and c.CodFiscale = @CodFiscCliente
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
-------------- reportSezionePers
	--Eliminazione report PDF
	PRINT 'DELETING ReportFisico .....'
	delete from ReportFisico 
	from ReportFisico rf
	inner join reportperclientedati rcd
	on 
		rcd.identificativo = rf.identificativo
	inner join reportpercliente rc
	on 
		rcd.idreport = rc.idreport
		and rcd.idcliente = rc.idcliente
	inner join cliente c
	on 
		c.idcliente = rc.idcliente
	where c.utente = @ReteAgente
		and c.CodFiscale = @CodFiscCliente
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
---------REPORTPERCLIENTEDATI
	PRINT 'DELETING reportperclientedati .....'
	delete from reportperclientedati
	from reportperclientedati rcd
	inner join reportpercliente rc
	on 
		rcd.idreport = rc.idreport
		and rcd.idcliente = rc.idcliente
	inner join cliente c
	on 
		c.idcliente = rc.idcliente
	where c.utente = @ReteAgente
		and c.CodFiscale = @CodFiscCliente
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
	select distinct rc.idreport into #rc
	from reportpercliente rc
	inner join cliente c
	on 
		c.idcliente = rc.idcliente
	where c.utente = @ReteAgente
		and c.CodFiscale = @CodFiscCliente
	--DELETE TABELLA REPORT
	PRINT 'DELETING reportpercliente 1.....'
	delete from reportpercliente
	from reportpercliente rc
	inner join cliente c
	on 
		c.idcliente = rc.idcliente
	where c.utente = @ReteAgente
		and c.CodFiscale = @CodFiscCliente
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
	--delete tabella Report
	PRINT 'DELETING Report.....'
	delete from Report
	from report r 
	inner join #rc
	on 
		r.idreport = #rc.idreport
	where r.utente = @ReteAgente
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
	drop table #rc
	COMMIT TRAN
END