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

CREATE PROCEDURE akuz.sp_UpdateCurrentMkbAndDiagnosisInDispanserisationInit(
    @DispanserisationInitId uniqueidentifier
)
AS
BEGIN

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



END
GO