CREATE OR REPLACE PROCEDURE rds.sp_deleteimportrrdirection(
    userid uuid
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_userid uuid := userid;
BEGIN
    
    DELETE
    FROM rds.t_import_rr_direction_benefits rd
        USING rds.t_import_elements ie
    WHERE ie.importelementsid = rd.importelementsid
      AND ie.users = p_userid;
    
    DELETE
    FROM rds.t_import_rr_direction rd
        USING rds.t_import_elements ie
    WHERE ie.importelementsid = rd.importelementsid
      AND ie.users = p_userid;
    
    DELETE
    FROM rds.t_import_elements
    WHERE users = p_userid
      AND type_ = (SELECT e.entityid
                   FROM vclib.t_entities e
                   WHERE e.entname = 'IMPORT_RR_DIRECTION' AND e.schema = 'RDS'
                   LIMIT 1);
    
    DELETE
    FROM rds.t_import_elements
    WHERE users = p_userid
      AND type_ = (SELECT e.entityid
                   FROM vclib.t_entities e
                   WHERE e.entname = 'IMPORT_RR_DIRECTION_BENEFITS' AND e.schema = 'RDS'
                   LIMIT 1);

END;
$$