﻿CREATE PROCEDURE [dbo].[sp_insertNewReportModel]
@nome as varchar(70),
@descrizione as varchar(250),
@flgModello as bit,
@IdReportModello as int,
@tpReport as smallint,
@utente as varchar(13)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @found as int
DECLARE @idReport as int
--esiste gia?
SELECT @found = count(*) FROM [dbo].[Report] WHERE Nome = @nome and Utente = @utente and IdReportModello = @IdReportModello
     IF(@found > 0)
        BEGIN
         SELECT @idReport=idReport FROM [dbo].[Report] WHERE Nome = @nome and Utente = @utente and IdReportModello = @IdReportModello
         UPDATE Report SET Descrizione = @Descrizione , DtCreazione = getDate() WHERE idReport = @idReport
         SELECT TOP 1 idReport FROM Report WHERE Nome = @nome and Utente = @utente and IdReportModello = @IdReportModello ORDER BY DtCreazione DESC
		END
	 ELSE
	     INSERT INTO [dbo].[Report]
	   		   ([Nome]
			   ,[Descrizione]
			   ,[DtCreazione]
			   ,[FlgModello]
			   ,[IdReportModello]
			   ,[TpReport]
			   ,[Utente])
		 VALUES
			   (@nome
			   ,@descrizione
			   ,getDate()
			   ,@flgModello
			   ,@IdReportModello
			   ,@tpReport
			   ,@utente)
         SELECT @@identity as idReport
END