ALTER PROCEDURE [dbo].[P_VERDICHTE_PR_AKT] (@p_user VARCHAR(20)) 
AS
	SET NOCOUNT ON
	DECLARE @ln_count NUMERIC(8) 
BEGIN

/***************************     Falls nötig,  Jahre in DT861 anlegen      *************************/

	INSERT INTO  dt861   
		( DI023119 , 
		DI023062 , 
		DI023063 , 
		DI023064 , 
		DI023065 , 
		DI023066 , 
		DI023067 , 
		DI023068 , 
		DI023069 , 
		DI023070 , 
		DI023071 , 
		DI023072 )  
	 SELECT pr , 
		jahr , 
		-- Objektschutz
		GETDATE(),			-- Anlagedatum
		GETDATE(),			-- Änderungsdatum
		775,			    -- rwdu
		@p_user,			  -- Anlagebenutzer
		@p_user,			  -- Änderungsbenutzer
		 NULL,			  -- Own.Liz.
		'',			     -- OSK
		775,			    -- Owner
		775,			    -- Group
		775			     -- Any    
        FROM (SELECT PR, JAHR
                FROM (SELECT DISTINCT
                             DI001395 PR,
                             cast(DATEPART(year, di001519) as numeric(10,0)) JAHR
                        FROM dt472
                       WHERE DI001395 IN
                                (SELECT PROJEKT FROM ##T_PPMS_RISIKO_VERD_39440 WHERE SESSIONID = @@SPID)
                      UNION
                      SELECT DISTINCT di028836 pr, di028692 jahr
                        FROM DT871
                       WHERE DI028836 IN
                                (SELECT PROJEKT FROM ##T_PPMS_RISIKO_VERD_39440 WHERE SESSIONID = @@SPID)) SRC
               WHERE NOT EXISTS
                            (SELECT 1
                               FROM DT861 TGT
                              WHERE     SRC.PR = tgt.DI023119
                                    AND SRC.JAHR = TGT.DI023062)) PR_YR;

		 -- Copy all values from 871 to 861, using 0 if record not found in 871
		UPDATE DT861
		SET	DI028831 = coalesce(planned_benefit,0),
			DI023173 = coalesce(achieved_benefit,0)
		FROM (
			SELECT SUM(coalesce(di028695,0)) planned_benefit, SUM(coalesce(di028706,0)) achieved_benefit,
				DI023119 pr_id, di023062 year_id
			FROM dt871 RIGHT OUTER JOIN dt861 ON 
				dt861.DI023119 = dt871.di028836
				AND dt861.di023062 = dt871.di028692 
			WHERE di023119 IN (SELECT PROJEKT FROM ##T_PPMS_RISIKO_VERD_39440 WHERE SESSIONID = @@SPID)
			GROUP BY DI023119, di023062) PAB
		WHERE di023119 = pr_id AND di023062 = year_id;

		
		
      -- Kosten verdichten, falls VGR existieren
    SELECT @ln_count = count(*) FROM dt466 WHERE DI001390 IN (SELECT PROJEKT FROM ##T_PPMS_RISIKO_VERD_39440 WHERE SESSIONID = @@SPID);
	IF @ln_count > 0 
	BEGIN 
		EXEC P_UPD_KOST_AUFW_ERL_AKT;
	END
      
	-- Budget aus Baseline aktualisieren
	EXEC P_UPD_BUDGET_BL;
      
	-- Risiken und Chancen verdichten
	EXEC P_VERD_RISIKEN_CHANCEN_AKT @p_user;
END
