Loop inside of query in mysql procedure. Is it possible?
I solved this writhing the following code:

drop procedure if exists populate;
delimiter $$
CREATE PROCEDURE populate (IN n INT, IN l INT, IN k INT)
BEGIN
  declare _k int unsigned DEFAULT 0;
  declare _n int unsigned DEFAULT 0;
  declare _l int unsigned DEFAULT 0;
  DECLARE _stmt TEXT DEFAULT 'INSERT INTO major_1 (';

  WHILE _n &lt; n DO set _n=_n+1;
    set _stmt = CONCAT(_stmt,'minor_',_n,'_id');
    IF _n&lt;n THEN set _stmt = CONCAT(_stmt,','); END IF;
  END WHILE;
  set _stmt = CONCAT(_stmt,') VALUES ');

  while _k &lt; k do set _k=_k+1;
    set _stmt = CONCAT(_stmt,'(');
    set _n=0; WHILE _n &lt; n do set _n=_n+1;
      SET _stmt = CONCAT(_stmt,CEIL(RAND()*l));
      IF _n&lt;n THEN set _stmt = CONCAT(_stmt,','); END IF;
    END WHILE;
    IF _k&lt;k THEN set _stmt = CONCAT(_stmt,'),');
    ELSE set _stmt = CONCAT(_stmt,');'); END IF;
  end while;

# code to debug:
# SELECT n,l,k,_stmt;

  SET @STMT = _stmt;
  PREPARE stmt FROM @stmt;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END $$
delimiter ;


And this can be used (for N=20,L=25,K=3) by command:

CALL populate(20,25,3);


Sources:

Loops in MySQL


  https://stackoverflow.com/questions/1485668/how-to-set-initial-value-and-auto-increment-in-mysql


Execution of text variable as query


  https://stackoverflow.com/questions/190776/how-to-have-dynamic-sql-in-mysql-stored-procedure