0

Using purely MySQL, I want to search and replace 'oldString' with 'newString' from and undetermined number of tables and columns. A search for my table prefix in information_schema, reveals all the tables that I need to look for.

I have the following trials: Querying DB table prefix on information_schema

SELECT TABLE_SCHEMA, TABLE_NAME 
FROM information_schema.TABLES WHERE table_name LIKE  '%mysite_www%'

Results:

+-----------------+----------------------------+
| TABLE_SCHEMA    | TABLE_NAME                 |
+-----------------+----------------------------+
| myDB            | mysite_www_moredata        |
| myDB            | mysite_www_data            |
| myDB            | mysite_www_urls            |
| myDB            | mysite_www_pages           |
| myDB            | mysite_www_feedback        |
| myDB            | mysite_www_comments        |
| myDB            | mysite_www_links           |
+-----------------+----------------------------+
Query results yields about 200 tables or so.

I want to take the results, filter it for a particular string and replace it with a new one. Replace 'oldString' with 'newString'.

For each TABLE_NAME, search for any column WHERE column LIKE '%oldString%'.

WHERE CONCAT(table1, table2, ... tableN) LIKE 'oldString';

For each column result, update 'oldString' to 'newString'.

UPDATE tableN SET columnN = REPLACE (columnN, '%oldString%', 'newString') WHERE URL LIKE '%oldString%';

I need to do this in pure MySQL as it will be a store procedure. Any assistance or tips is greatly appreciated.

4

1 回答 1

1

因此,通过使用 information_Schema,您可以查询表和列以获得结果。我在这个SO 答案中做了类似的事情。

本质上是查询 information_schema 并让 MySQL 为您构建 SQL。上面的链接应该可以帮助您。

更新:

您可以使用以下查询来构造所有更新语句

SELECT CONCAT('UPDATE ',TABLENAME, 'SET ', COLUMN_NAME,'= REPLACE (',COLUMN_NAME, '''%oldString%'', ''newString'') WHERE URL LIKE ''%oldString%''')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE  '%somecriteria%' AND COLUMN_NAME LIKE '%somecriteria%'

将这些结果字符串插入临时表,然后使用此处描述的技术循环执行字符串的行

于 2013-08-23T00:55:40.800 回答