How to split comma separated text in MySQL stored procedure

后端 未结 9 1088
臣服心动
臣服心动 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:57

    You can do it two ways:

    1. SQL Library
    2. Natively with REGEXP
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-05 12:00

    A bit strange but:

    SET @i = 1;
    set @str = 'a,b,c,d,e,f,g,h';
    
    select temp.length into @length from 
    (select
            ROUND(   
                (
                    LENGTH(dt.data)
                    - LENGTH( REPLACE (dt.data, ",", "") ) 
                ) / LENGTH(",")        
            )+1 AS length   
         from (select @str as data) dt
     ) temp;
    
    SET @query = CONCAT('select substring_index(
        substring_index(@str, '','', seq), 
        '','', 
        -1
      ) as letter from seq_', @i, '_to_',@length);
    
    PREPARE q FROM @query;
    EXECUTE q;
    
    0 讨论(0)
提交回复
热议问题