Loop n times without using a stored procedure

后端 未结 4 891
闹比i
闹比i 2021-02-04 03:10

How can I write a loop that runs n times in MySql without using a stored procedure.

This is how I do it with a stored procedure:

DELIMITER $$
DROP PR         


        
4条回答
  •  情深已故
    2021-02-04 03:26

    As mentioned by Berd you could do it with the built in sequence but it's a bit strange:

    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;
    

提交回复
热议问题