CREATE  PROCEDURE [dbo].[sp_getDocuments_ByUtenteAndTipoReport]
@tpReport as int,
@utente as varchar(13),
@codiceFiscale as varchar(16) = null
AS
BEGIN
IF(@codiceFiscale is not null)
	SELECT     Cliente.IdCliente, ReportperClienteDati.Identificativo, ReportperClienteDati.FlgArchiviato AS stato, Cliente.Nominativo, 
						  ReportperClienteDati.DtCreazione, ReportperClienteDati.Note, TipologiaReport.Descrizione AS TipologiaReport
	FROM         Cliente INNER JOIN
						  ReportPerCliente ON Cliente.IdCliente = ReportPerCliente.IdCliente INNER JOIN
						  ReportperClienteDati ON ReportPerCliente.IdReport = ReportperClienteDati.IdReport AND 
						  ReportPerCliente.IdCliente = ReportperClienteDati.IdCliente INNER JOIN
						  Report ON ReportPerCliente.IdReport = Report.IdReport INNER JOIN
						  TipologiaReport ON Report.TpReport = TipologiaReport.TpReport
		WHERE (TipologiaReport.TpReport = @tpReport) 
			   AND (Cliente.Utente = @utente) 
			   AND Cliente.CodFiscale = @codiceFiscale
			   order by ReportperClienteDati.DtCreazione DESC
ELSE 
	SELECT     Cliente.IdCliente, ReportperClienteDati.Identificativo, ReportperClienteDati.FlgArchiviato AS stato, Cliente.Nominativo, 
						  ReportperClienteDati.DtCreazione, ReportperClienteDati.Note, TipologiaReport.Descrizione AS TipologiaReport
	FROM         Cliente INNER JOIN
						  ReportPerCliente ON Cliente.IdCliente = ReportPerCliente.IdCliente INNER JOIN
						  ReportperClienteDati ON ReportPerCliente.IdReport = ReportperClienteDati.IdReport AND 
						  ReportPerCliente.IdCliente = ReportperClienteDati.IdCliente INNER JOIN
						  Report ON ReportPerCliente.IdReport = Report.IdReport INNER JOIN
						  TipologiaReport ON Report.TpReport = TipologiaReport.TpReport
		WHERE (TipologiaReport.TpReport = @tpReport) 
			   AND (Cliente.Utente = @utente) 
			   order by ReportperClienteDati.DtCreazione DESC
END