I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:
SELECT * FROM * WHERE * LIKE \'%stuff%\'
Even if the following proposal should not be considered as a final solution you can achieve the goal by doing something like this:
SET SESSION group_concat_max_len = 1000000;
SET @search = 'Text_To_Search';
DROP table IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
(SELECT
CONCAT('SELECT \'',TABLE_NAME,'\' as \'table_name\',\'',COLUMN_NAME,'\' as \'column_name\',CONVERT(count(*),char) as \'matches\' FROM `',
TABLE_NAME,'` where `',COLUMN_NAME,'` like \'%',@search,'%\' UNION ') as 'query'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' limit 1000000);
set @query = (SELECT GROUP_CONCAT(t1.`query` SEPARATOR '') as 'final_query' from table1 t1 limit 1);
set @query = (SELECT SUBSTRING(@query, 1, length(@query) - 7));
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Please remember that:
Options: group_concat_max_len and limit 1000000 not always are needed, it will depends of your server/IDE configuration. Just in case I added them.
After executing this you will get a 3 column response: [table_name], [column_name], [matches]
Column 'matches' is the number of occurrences in the given table/column.
This query is very fast.
DISCLAIMER: It would be useful only for personal use, in other words please don't use it in a production system, because it is sensitive to SQL Injection attacks given that the search parameter is concatenated with other strings. If you want to create a prod. ready function, then you will need to create a store procedure with a LOOP.