SELECT card.RealDateOut, ev.EventID
INTO #Events
FROM AKUZ.T_MOVEMENTS_DIVISION_CARD card
LEFT JOIN AKUZ.T_MOVEMENT m ON card.Movement = m.MovementID
LEFT JOIN AKUZ.T_EVENT_BASE ev ON m.EmergencyEvent = ev.EventID
WHERE
card.RealDateOut IS NOT NULL
AND ev.CloseDate IS NULL
AND 
(card.MovementTypeOut IN (3, 6, 7, 15, 99))
GO

UPDATE e 
SET e.CloseDate = ee.RealDateOut
FROM AKUZ.T_EVENT_BASE e
JOIN #Events ee on ee.EventID = e.EventID
GO

DROP TABLE #Events
GO

SELECT card.DatOut, ev.EventID
INTO #Events
FROM AKUZ.T_MOVEMENT_RESULT card
LEFT JOIN AKUZ.T_MOVEMENT m ON card.MedicalcardRegistration = m.MovementID
LEFT JOIN AKUZ.T_EVENT_BASE ev ON m.EmergencyEvent = ev.EventID
WHERE
card.DatOut IS NOT NULL
AND ev.CloseDate IS NULL
AND 
(card.HospitalOutcome IN(23701, 23703, 23704, 23707, 23708, 23709, 23710, 23711, 23712,
23713, 23714, 23715, 23716, 23718, 23720, 23721))
GO

UPDATE e 
SET e.CloseDate = ee.DatOut
FROM AKUZ.T_EVENT_BASE e
JOIN #Events ee on ee.EventID = e.EventID
GO

DROP TABLE #Events
GO