DO
$$
BEGIN
	IF EXISTS 
	(
		SELECT * 
        FROM   pg_proc p
		WHERE  p.proname = 'sp_UpdateDweToReType'
	)
	THEN
		DROP FUNCTION akuz.sp_UpdateDweToReType(UUID, UUID);
	END IF;
END;
$$ 
LANGUAGE plpgsql;

-- =============================================
-- Author:  Michael Panin
-- Create date: 2023/08/08
-- Description: Смена типа MEDICAL_EXAMINATION_RE на DOCTOR_WARD_EXAMINATION
-- =============================================

CREATE OR REPLACE FUNCTION public.sp_UpdateDweToReType
(
	"newDweId" UUID -- Идентификатор нового DOCTOR_WARD_EXAMINATION
,	"oldDweId" UUID -- Идентификатор старого DOCTOR_WARD_EXAMINATION
)
RETURNS void
AS
$$ 
BEGIN

    UPDATE AKUZ.T_MEDICAL_RECORD 
	SET type_ = (SELECT EntityID
                 FROM   VCLib.T_ENTITIES
                 WHERE  EntName = 'MEDICAL_EXAMINATION_RE' AND Schema = 'AKUZ')
	WHERE MedicalRecordID = "oldDweId"

    DELETE FROM AKUZ.T_DOCTOR_WARD_EXAMINATION
    WHERE MedicalRecordID = "oldDweId"

    INSERT INTO AKUZ.T_MEDICAL_EXAMINATION_RE (MedicalRecordID, MedicalExaminationMain)
    VALUES("oldDweId", "newDweId")

END;
$$ 
LANGUAGE plpgsql;
