I am trying to insert rows into a db table through a stored procedure. My table contains more than 500000 rows so when I execute the procedure, it takes more than 4h executing.
Knowing that I am using Xampp server, MySQL as database management system and HeidiSQL
to manipulate the db.
Below you see the procedure script. Is there any issue with the code or should I add other things.
Thanks for your help in advance.
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE post_id BIGINT;
DECLARE v_id BIGINT;
DECLARE done INT DEFAULT 0;
DECLARE msg varchar(10000) DEFAULT "";
DEClARE post_cursor CURSOR FOR
SELECT distinct po.post_id FROM wp_postmeta po;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET finished = 2;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
Open post_cursor;
get_posts: LOOP
FETCH post_cursor INTO post_id;
select CONCAT('postid', post_id) ;
IF done = 1 THEN
LEAVE get_posts;
END IF;
SET v_id = (select MAX (meta_id) from wp_postmeta) +1 ;
INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value) VALUES (v_id, post_id ,"_company_name", "blabla");
SET done = 0;
END LOOP;
CLOSE post_cursor;
END
2
Answers
I would do it this way:
No cursor needed, just rely on INSERT…SELECT.
No DISTINCT needed, since you know there’s exactly one row for each post in the
wp_posts
table.No
max(meta_id)+1
needed, just rely on the auto-increment to do its job.wp_postmeta has an auto_incrememnt on meta_id, so use
The main point is the
GROUP BY
that garantees that only 1 post _id is inserteddb<>fiddle here