IF EXISTS (SELECT *
           FROM dbo.sysobjects
           WHERE id = OBJECT_ID(N'[akuz].[sp_UpdateCurrentMkbAndDiagnosisInMentalDispInit]'))
    DROP PROCEDURE [akuz].[sp_UpdateCurrentMkbAndDiagnosisInMentalDispInit]
GO

CREATE PROCEDURE AKUZ.sp_UpdateCurrentMkbAndDiagnosisInMentalDispInit(
	@DispanserisationInitId uniqueidentifier
)
AS 
BEGIN 

    SET NOCOUNT ON;

	WITH cte AS 
    (
	    SELECT 
		    mov.Mkb AS Mkb,
		    mov.Diagnosis as Diagnosis,
		    mov.DispanserisationInit
	    FROM AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mov
	    WHERE 
		    mov.DispanserisationInit = @DispanserisationInitId
		    AND NOT EXISTS (
			    SELECT 1
			    FROM AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mov2
			    WHERE mov.DispanserisationInit = mov2.DispanserisationInit
			    AND mov2.DateEditing > mov.DateEditing)
	)
	UPDATE di
	SET 
	    CurrentDiagnosis = COALESCE(cte.Diagnosis, di.Diagnosis),
        CurrentMkb       = COALESCE(cte.Mkb, di.Mkb)
	FROM AKUZ.T_MENTAL_DISPANSERISATION_INIT di
	LEFT JOIN cte on di.MedicalRecordID = cte.DispanserisationInit
    WHERE di.MedicalRecordID = @DispanserisationInitId

END 
GO