CREATE PROCEDURE [dbo].[sp_insertNewReportModelNew]
@nome as varchar(70),
@descrizione as varchar(250),
@flgModello as bit,
@IdReportModello as int,
@tpReport as smallint,
@utente as varchar(13),
@idCliente as int = null,
@Privacy as tinyint
AS
BEGIN
SET NOCOUNT ON;
DECLARE @found as int
DECLARE @idReport as int
--esiste gia?
	--step 1
     SELECT @idReport=IdReport  FROM [dbo].[Report] WHERE Nome = @nome and Utente = @utente and IdReportModello = @IdReportModello
     IF(@idReport > 0)
        BEGIN
          UPDATE Report SET Descrizione = @Descrizione , DtCreazione = getDate(), Privacy = @Privacy WHERE idReport = @idReport
             --step 2
			DELETE FROM [dbo].[ReportSezionePers]
				  WHERE IdReport = @idReport and Utente = @utente
			--step 3
			select @found = count(*) from [dbo].[ReportPerCliente] where IdCliente = @idCliente and IdReport = @idReport
			if(@found > 0)
				UPDATE [dbo].[ReportPerCliente]
						SET DtAssociazione = getdate() 
				WHERE IdCliente = @idCliente and IdReport = @idReport
			else
			INSERT INTO [dbo].[ReportPerCliente]
					   ([DtAssociazione]
					   ,[IdReport]
					   ,[IdCliente])
				 VALUES
					   (getdate()
					   ,@idReport
					   ,@idCliente)
		END
	 ELSE
		BEGIN
	      INSERT INTO [dbo].[Report]
	   		   ([Nome]
			   ,[Descrizione]
			   ,[DtCreazione]
			   ,[FlgModello]
			   ,[IdReportModello]
			   ,[TpReport]
			   ,[Utente]
			   ,[Privacy])
		  VALUES
			   (@nome
			   ,@descrizione
			   ,getDate()
			   ,@flgModello
			   ,@IdReportModello
			   ,@tpReport
			   ,@utente
			   ,@Privacy)
            SELECT @idReport = @@identity 
            --step 2
			--DELETE FROM [dbo].[ReportSezionePers]
			--	  WHERE IdReport = @idReport and Utente = @utente
			--step 3
			--select @found = count(*) from [dbo].[ReportPerCliente] where IdCliente = @idCliente and IdReport = @idReport
			--if(@found > 0)
				--UPDATE [dbo].[ReportPerCliente]
						--SET DtAssociazione = getdate() 
				--WHERE IdCliente = @idCliente and IdReport = @idReport
			--else
			INSERT INTO [dbo].[ReportPerCliente]
					   ([DtAssociazione]
					   ,[IdReport]
					   ,[IdCliente])
				 VALUES
					   (getdate()
					   ,@idReport
					   ,@idCliente)
	END	
	return    @idReport
	END