﻿-- Stored procedure
CREATE PROCEDURE [dbo].[SP_PDF_INSERT]
	@idProvenienza varchar(1) ,	-- SELECT * FROM ProvenienzaPdf
	@TpReport smallint ,		-- SELECT * FROM TipologiaReport
	@idStato varchar(1) ,		-- SELECT * FROM StatoPdf	
	@CodicePB varchar(6) ,
	@Rete varchar (1) ,
	@NumeroPagine  int ,
	@Note varchar(4000),  
	@Image AS image = NULL,
	@chiaviClientePb as varchar(4000) = null,
	@chiaveNucleo AS BIGINT = NULL,
	@CodiceContratto as varchar(4000) = null
AS
BEGIN
	SET NOCOUNT ON; 
	BEGIN TRANSACTION
	DECLARE @IdPdf AS BIGINT
	INSERT INTO DocumentiPdf
           ([dtCreazione]
           ,[idProvenienza]
           ,[TpReport]
           ,[idStato]
           ,[idArchivio]
           ,[dtRestore]
           ,[CodicePB]
           ,[Rete]
           ,[NumeroPagine]
           ,[Note])
     VALUES
           (getdate()
           ,@idProvenienza
           ,@TpReport
           ,@idStato
           ,'O' -- SELECT * FROM ArchivioPdf
           ,null
           ,@CodicePB
           ,@Rete
           ,@NumeroPagine
           ,@Note)
	SET @IdPdf = @@identity
	INSERT INTO ImagePdf (idPdf,[Image]) VALUES (@IdPdf,@Image)           
	INSERT INTO ClientiPdf         
		SELECT @IdPdf as IdPdf,s.value as chiaveClientePb, c.value as CodiceContratto  
		FROM Split(',',@chiaviClientePb) AS s left join Split(',',@CodiceContratto) AS c ON s.RowID=c.RowID
    IF @chiaveNucleo IS NOT NULL
    BEGIN
		INSERT INTO NucleiPdf (idPdf,chiaveNucleo) VALUES(@IdPdf,@chiaveNucleo)
	END
    INSERT INTO LogPdf (idPdf,dtstamp,idLogEvent,idProvenienza )	 
		SELECT  @IdPdf,
				GETDATE(),
				1	as idLogEvent,
				@idProvenienza 
	select  @IdPdf 
    COMMIT TRANSACTION
END