简体   繁体   中英

How can I run a SQL UPDATE against the results of query that captures table names from INFORMATION_SCHEMA.TABLES?

I'm looking to replace a string in a CMS multi-site database across a common set of tables. Here is the initial query to collect the target tables:

SELECT TABLE_NAME as target_table
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_content'

...against the results of which I'd like to run the following:

UPDATE target_table
SET title = replace(title, 'SEARCH_STRING', 'REPLACE_STRING')
WHERE title LIKE ('%SEARCH_STRING%');

Thanks in advance for the assist!

For a one off, a workable approach is to use SQL to generate a set of SQL statements.

Assuming that the table_schem and table_name don't contain backtick characters, and if your SEARCH_STRING and REPLACE_STRING don't contain single quotes (or are properly escaped), we could do something like this:

SELECT CONCAT('UPDATE `',t.table_schema,'`.`',t.table_name,'` c'
       ,' SET c.title = REPLACE(c.title, ''SEARCH_STRING'', ''REPLACE_STRING'')'
       ,' WHERE c.title LIKE (''%SEARCH_STRING%'') ;') AS `-- stmt`
  FROM INFORMATION_SCHEMA.TABLES t
 WHERE t.table_name LIKE '%_content'
   AND t.table_schema NOT IN ('information_schema','mysql','performance_schema')
 ORDER BY t.table_schema, t.table_name

we can save the results from the query into a file. and then submit the SQL statements in the file to the MySQL server.

(I think I would be using INFORMATION_SCHEMA.COLUMNS, with tables containing column named 'title' as well as the table_name matching a pattern, but the approach is the same.


Note that this cannot be accomplished in a single SQL statement; the query to get the list of tables is going to have to be a separate statement, separated from the execution of the actual UPDATE statement(s).

EDIT I just took a look at the answer linked to in the question; that is totally unrelated. There's nothing there that would apply to the problem we are trying to solve here.

Because of the way SQL is processed (parse, syntax check, semantic check, determine execution plan, then execute)... identifiers (eg table names) must be supplied as tokens in the SQL text. Identifiers cannot be supplied as values at execution time. That's why we need separate statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM