How to split comma separated text in MySQL stored procedure

后端 未结 9 1127
臣服心动
臣服心动 2020-12-05 11:30

How to split comma separated text (list of IDs) in MySQL stored procedure to use result in SQL \"IN\" statement.

SELECT * FROM table WHERE table.id IN (split         


        
9条回答
  •  醉话见心
    2020-12-05 11:58

    You could try this MySql example. Before you use it, put some type safety checks in there (i.e. check id is integer, or match against regular expression before insert).

     # BEGIN split statements ids
     DECLARE current_pos INT DEFAULT 1;
     DECLARE delim CHAR DEFAULT ',';
     DECLARE current CHAR DEFAULT '';
     DECLARE current_id VARCHAR(100) DEFAULT '';;
     CREATE TEMPORARY TABLE ids (`id` VARCHAR(100));
     split_ids: LOOP
      SET current = MID(statement_ids, current_pos, 1);
      IF (current_pos = LENGTH(statement_ids)) THEN
       IF current != delim THEN SET current_id = CONCAT(current_id,current); END IF;
       INSERT INTO ids(id) VALUES (current_id);
       LEAVE split_ids;
      END IF;
      IF current = delim THEN
       INSERT INTO ids(id) VALUES (current_id);
       SET current_id = '';
      ELSE
       SET current_id = CONCAT(current_id,current);
      END IF;
      SET current_pos = current_pos+1;
     END LOOP split_ids;
     # END split statement ids
    
     # to check ids are correct
     SELECT * FROM ids;
    
     # to use the ids:
     SELECT * FROM statements WHERE id IN (SELECT id FROM ids);
    

提交回复
热议问题