DROP FUNCTION IF EXISTS fn_GetParentXRay;
CREATE Function fn_GetParentXRay
(
	"RecordID" UUID
)
RETURNS UUID As 
$$
Begin
	RETURN
	(
		select t0.MedicalRecordID 
		FROM akuz.T_X_RAY_DIAGNOSTICS t0
		LEFT JOIN 
			akuz.T_DIAGNOSTICS_RESULTS t4 
			ON t4.MedicalRecordID = t0.MedicalRecordID 
		LEFT JOIN 
			akuz.T_AMBULANCE_CARD_RECORD t3 
			ON t3.MedicalRecordID = t0.MedicalRecordID
		Inner JOIN 
			akuz.T_X_RAY_DIAGNOSTICS a 
			on a.MedicalRecordID = "RecordID"
		LEFT JOIN 
			akuz.T_DIAGNOSTICS_RESULTS dr 
			ON dr.MedicalRecordID = a.MedicalRecordID
		LEFT JOIN 
			akuz.T_AMBULANCE_CARD_RECORD acr 
			ON acr.MedicalRecordID = a.MedicalRecordID
		WHERE acr.AmbulanceEvent = t3.AmbulanceEvent 
		and acr.PostingDate = t3.PostingDate 
		and dr.Research = t4.Research 
		and t0.MedicalRecordID > "RecordID"
		and not exists 
		(
			select 1 from akuz.T_REGISTER_ITEM where service = t0.MedicalRecordID limit 1
		) 
		and not exists 
		(
			select 1 from akuz.T_REGISTER_ITEM where service = t0.Parent limit 1
		)
		order by t0.MedicalRecordID desc
		Limit 1
	);
End;
$$ Language plpgsql stable;