CREATE OR REPLACE PROCEDURE public.sp_updatevznmessage(
    id uuid
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_id uuid := id;
BEGIN
    
    UPDATE rds.t_message_to_nosology_service m
    SET status = 0
    WHERE m.status = 4
      AND EXISTS (SELECT 1
                  FROM rds.t_patient_drug_demand pdd
                  JOIN rds.t_pharmacy_drug_demand phdd ON phdd.pharmacydrugdemandid = pdd.pharmacydrugdemand
                  JOIN rds.t_drug_demand dd ON dd.drugdemandid = phdd.drugdemand
                  WHERE pdd.patientdrugdemandid = m.objid
                    AND dd.drugrequest = p_id
                 );

END;
$$