DO $$ 
DECLARE 
    cnpdf INT;
    cnEnt INT;
BEGIN
    SELECT entityid INTO cnpdf 
    FROM vclib.T_ENTITIES 
    WHERE EntName = 'CN_PDF' 
    LIMIT 1;

    SELECT entityid INTO cnEnt 
    FROM vclib.T_ENTITIES
    WHERE EntName = 'CARD_NOTE' 
    LIMIT 1;

    CREATE TEMP TABLE temp_medical_records AS
    SELECT cn.MedicalRecordID
    FROM akuz.T_MEDICAL_RECORD mr
    JOIN akuz.T_CARD_NOTE cn ON mr.MedicalRecordID = cn.MedicalRecordID
    JOIN akuz.T_RECIPE r ON r.MedicalRecordID = cn.AmbulanceCardRecord
    WHERE mr.type_ = cnEnt;

    UPDATE akuz.T_MEDICAL_RECORD mr
    SET type_ = cnpdf
    WHERE mr.MedicalRecordID IN (SELECT MedicalRecordID FROM temp_medical_records);

END $$;