2

I have a query which lists users IDs based on some criteria.

Now I want to insert every user ID into different table. I was thinking of a loop which would go through the list and insert a row one by one.

This is my select query:

SELECT s.id, s.name FROM students s
limit 10000;

How can I make a loop out of that. How to get to the values out of select statement in the loop?

DROP PROCEDURE IF EXISTS loop_date;
DELIMITER //  
CREATE PROCEDURE loop_date()
BEGIN
DECLARE i INT DEFAULT 1; 
WHILE (number_of_students < 10000) DO
INSERT INTO users (student_id,student_name) VALUES (X?, Y?);
SET i = i+1;
END WHILE;
END;
//
DELIMITER ;

1 Answer 1

2

You can INSERT ... SELECT in a single statement, instead of INSERT ... VALUES.

INSERT INTO users (student_id,student_name)
SELECT s.id, s.name FROM students s
limit 10000;

See https://dev.mysql.com/doc/refman/8.0/en/insert-select.html

Sign up to request clarification or add additional context in comments.

1 Comment

It worked, I also had to add a constant value but did that with: INSERT INTO users(student_id, university_id) SELECT s.id, '1' FROM students s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.