Skip to content

Instantly share code, notes, and snippets.

@well-it-wasnt-me
Last active March 1, 2024 14:09
Show Gist options
  • Save well-it-wasnt-me/c5d8959b2ef94d559e2a65fd4f78e68d to your computer and use it in GitHub Desktop.
Save well-it-wasnt-me/c5d8959b2ef94d559e2a65fd4f78e68d to your computer and use it in GitHub Desktop.
Small mysql procedure to search and replace string in all tables inside a specific database. I had to do this recenty because of a moving wordpress installation in another path
DELIMITER //
CREATE PROCEDURE search_replace_db(IN db_name VARCHAR(255), IN search_for VARCHAR(255), IN replace_with VARCHAR(255))
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tableName VARCHAR(100);
DECLARE columnName VARCHAR(100);
DECLARE cur CURSOR FOR
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = db_name
AND (COLUMN_TYPE LIKE '%text%' OR COLUMN_TYPE LIKE '%varchar%');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO tableName, columnName;
IF done THEN
LEAVE read_loop;
END IF;
SET @sql = CONCAT('UPDATE `', tableName, '` SET `', columnName, '` = REPLACE(`', columnName, '`, `', search_for, '`, `', replace_with, '`) WHERE `', columnName, '` LIKE search_for;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur;
END //
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment