CREATE OR REPLACE PROCEDURE akuz.sp_updatecurrentmkbanddiagnosisindispanserisationinit(
    dispanserisationinitid uuid
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_dispanserisationinitid uuid := dispanserisationinitid;
BEGIN

    WITH cte AS (SELECT mov.DispanserisationInit, mov.Mkb, mov.Diagnosis
                 FROM akuz.T_DISPANSERISATION_MOVENMENT mov
                 WHERE mov.DispanserisationInit = p_dispanserisationinitid
                   AND NOT EXISTS (SELECT 1
                                   FROM akuz.T_DISPANSERISATION_MOVENMENT mov2
                                   WHERE mov2.DateEditing > mov.DateEditing
                                     AND mov.DispanserisationInit = mov2.DispanserisationInit))
    UPDATE akuz.t_dispanserisation_init di
    SET
        currentdiagnosis = COALESCE((SELECT cte.diagnosis FROM cte LIMIT 1),di.diagnosis),
        currentmkb = COALESCE((SELECT cte.mkb FROM cte LIMIT 1),di.mkb)
    WHERE di.medicalrecordid = p_dispanserisationinitid;


END;
$$;