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

CREATE PROCEDURE AKUZ.sp_UpdateCurrentsInPsychoDispInit(
    @DispanserisationInitId uniqueidentifier
)
AS 
BEGIN
    -- Создаем временную таблицу для хранения актуальных данных
    CREATE TABLE #TempDispData (
        DispanserisationInit uniqueidentifier PRIMARY KEY,
        Mkb VARCHAR(255),
        Diagnosis VARCHAR(255),
        SurveillanceType INT,
        DnGroup INT,
        MentalDispanserisationType INT,
        DnSubGroup INT
    );

    -- Заполняем временную таблицу актуальными записями
    INSERT INTO #TempDispData
    SELECT 
        mmov.DispanserisationInit,
        mmov.Mkb,
        mmov.Diagnosis,
		mov.SurveillanceType,
		mov.DnGroup,
		mov.MentalDispanserisationType,
		mov.DnSubGroup
    FROM AKUZ.T_PSYCHO_DISPANSERISATION_MOVENMENT mov
    JOIN AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mmov
		ON mov.MedicalRecordID = mmov.MedicalRecordID
    WHERE 
        mmov.DispanserisationInit = @DispanserisationInitId
        AND NOT EXISTS (
            SELECT 1
            FROM AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mov2
            WHERE mmov.DispanserisationInit = mov2.DispanserisationInit
            AND mov2.DateEditing > mmov.DateEditing
        );

    -- Обновляем T_MENTAL_DISPANSERISATION_INIT
    UPDATE di
    SET 
        di.CurrentMkb = COALESCE(tmp.Mkb, di.Mkb),
        di.CurrentDiagnosis = COALESCE(tmp.Diagnosis, di.Diagnosis)
    FROM AKUZ.T_MENTAL_DISPANSERISATION_INIT di
    LEFT JOIN #TempDispData tmp ON di.MedicalRecordID = tmp.DispanserisationInit
    WHERE di.MedicalRecordID = @DispanserisationInitId;

    -- Обновляем T_PSYCHO_DISPANSERISATION_INIT
    UPDATE pdi
    SET
        pdi.CurrentSurveillanceType = COALESCE(tmp.SurveillanceType, pdi.SurveillanceType),
        pdi.CurrentDnGroup = COALESCE(tmp.DnGroup, pdi.DnGroup),
        pdi.CurrentMentalDispanserisationType = COALESCE(tmp.MentalDispanserisationType, pdi.PsychoDispanserisationType),
        pdi.CurrentDnSubGroup = COALESCE(tmp.DnSubGroup, pdi.DnSubGroup)
    FROM AKUZ.T_PSYCHO_DISPANSERISATION_INIT pdi
    LEFT JOIN #TempDispData tmp ON pdi.MedicalRecordID = tmp.DispanserisationInit
    WHERE pdi.MedicalRecordID = @DispanserisationInitId;

    -- Удаляем временную таблицу
    DROP TABLE #TempDispData;
END 
GO
