Created
April 17, 2019 16:25
-
-
Save wturnerharris/0d395ec0f49ead91a9a7038532fbaae5 to your computer and use it in GitHub Desktop.
Here's a mysql stored procedure to loop through the results of a select query that returns ids and performs an additional operation on each id.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DROP PROCEDURE IF EXISTS migrateById; | |
DELIMITER $$ | |
CREATE PROCEDURE migrateById() | |
BEGIN | |
DECLARE done INT DEFAULT FALSE; | |
DECLARE _post_id INT; | |
DECLARE migrate_ids CURSOR FOR | |
# modify the select statement to returns IDs, which will be assigned the variable `_post_id` | |
# the following statement gets all wp attachments that are missing attachment metadata | |
SELECT DISTINCT ID FROM wp_posts WHERE post_type = "attachment" AND ID NOT IN ( SELECT post_id FROM wp_postmeta WHERE meta_key = "_wp_attachment_metadata" AND meta_value IS NOT NULL); | |
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE; | |
OPEN migrate_ids; | |
read_loop: LOOP | |
FETCH migrate_ids INTO _post_id; | |
IF done THEN | |
LEAVE read_loop; | |
END IF; | |
# modify the insert statement to perform your operation with the `_post_id` | |
# the following insert statement adds missing metadata in wordpress | |
INSERT INTO `wp_postmeta` (`post_id`, `meta_key`, `meta_value`) | |
VALUES | |
(_post_id, 'mapped_key', 'mapped_value'); | |
SET done=FALSE; | |
END LOOP; | |
CLOSE migrate_ids; | |
END; $$ | |
CALL migrateById(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment