SQL split values to multiple rows

前端 未结 9 1392
刺人心
刺人心 2020-11-21 05:28

I have table :

id | name    
1  | a,b,c    
2  | b

i want output like this :

id | name    
1  | a    
1  | b    
1  | c             


        
9条回答
  •  广开言路
    2020-11-21 05:49

    CREATE PROCEDURE `getVal`()
    BEGIN
            declare r_len integer;
            declare r_id integer;
            declare r_val varchar(20);
            declare i integer;
            DECLARE found_row int(10);
            DECLARE row CURSOR FOR select length(replace(val,"|","")),id,val from split;
            create table x(id int,name varchar(20));
          open row;
                select FOUND_ROWS() into found_row ;
                read_loop: LOOP
                    IF found_row = 0 THEN
                             LEAVE read_loop;
                    END IF;
                set i = 1;  
                FETCH row INTO r_len,r_id,r_val;
                label1: LOOP        
                    IF i <= r_len THEN
                      insert into x values( r_id,SUBSTRING(replace(r_val,"|",""),i,1));
                      SET i = i + 1;
                      ITERATE label1;
                    END IF;
                    LEAVE label1;
                END LOOP label1;
                set found_row = found_row - 1;
                END LOOP;
            close row;
            select * from x;
            drop table x;
    END
    

提交回复
热议问题