Using MySQL Loop to Insert Variable Rows into a Table
Using MySQL Loop to Insert Variable Rows into a Table
Introduction: MySQL’s flexibility allows us to create dynamic solutions for data insertion tasks. In this article, we’ll explore how to use a MySQL stored procedure with parameters to insert a customizable number of rows into a sample table. By accepting an external parameter, the stored procedure becomes more versatile and adaptable to different use cases.

Step 1: Creating a Sample Table: Let’s start by creating a sample table named example_table with columns such as id, name, and value. Execute the following SQL command to create the table:
CREATE TABLE example_table (
id INT PRIMARY KEY,
name VARCHAR(50),
value INT
);Step 2: Writing the MySQL Loop with Parameters: Now, let’s write a MySQL stored procedure that accepts an insert_count parameter to determine the number of rows to insert. Below is the MySQL code for the modified stored procedure:
DELIMITER //
CREATE PROCEDURE insert_rows(IN insert_count INT)
BEGIN
DECLARE counter INT DEFAULT 1;
WHILE counter <= insert_count DO
INSERT INTO example_table (id, name, value) VALUES (counter, CONCAT('Name_', counter), counter * 10);
SET counter = counter + 1;
END WHILE;
END //
DELIMITER ;In this version of the stored procedure, insert_count is declared as an input parameter, allowing the user to specify the number of rows to insert.
Step 3: Executing the Stored Procedure with Parameter: Execute the modified stored procedure by providing the desired number of rows to insert. For example, to insert 50 rows:
CALL insert_rows(50);Step 4: Verifying the Results: Verify the inserted data by running a SELECT query:
SELECT * FROM example_table;Conclusion: In this article, we’ve enhanced the MySQL stored procedure by adding a parameter, making it more flexible and adaptable to different scenarios. By allowing external input for the number of rows to insert, this approach provides a dynamic solution for data insertion tasks.






