Posted: July 28, 2010 at 2:09 AM by jbuda
Tags: Miscellaneous
Just a small MySQL stored procedure i find my using often to do a database wide search and replace on. The function expects three parameters, the database to use, the string to find and the string to replace.
Pretty simple and saves me alot of time!
BEGIN
/*
PARAMETERS EXPECTED
- IN p_db VARCHAR
- IN p_from VARCHAR
- IN p_to VARCHAR
*/
DECLARE l_end INT DEFAULT 0;
DECLARE l_tablename VARCHAR(200);
DECLARE l_columnname VARCHAR(200);
/*
get a list of all the columns within the database insert into cursor
*/
DECLARE c_columns CURSOR FOR
SELECT table_name, column_name
FROM information_schema.columns
WHERE information_schema.columns.table_schema = p_db;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET l_end = 1;
/*
step through cursor and check the tables for columns with the url in
*/
OPEN c_columns;
columns_loop: LOOP
FETCH c_columns INTO l_tablename, l_columnname;
IF l_end = 1 THEN
LEAVE columns_loop;
END IF;
SET @d = CONCAT("UPDATE `",p_db,"`.",l_tablename," SET ",l_columnname," = REPLACE(",l_columnname,",\'",p_from,"\',\'",p_to,"\');");
SET @sql = @d;
PREPARE stat FROM @sql;
EXECUTE stat;
DEALLOCATE PREPARE stat;
END LOOP columns_loop;
CLOSE c_columns;
END

Apr 6, 2011 at 2:58 AM Hi, Thanks for this script, it really helped. The only thing I would suggest is adding data_type check for columns in the where clause in line 20 if the data to be replaced is a string. It makes the procedure much faster. Thanks, Brij
Apr 6, 2011 at 3:06 AM @Brij. Thanks for the pointer, will update the snippet to reflect your suggestion. Janusz