Search the entire database for a specified string in MySQL

Sometimes, you need to search for a certain string from the entire MySQL library, but you don't know which field in which table, use the following stored procedure, So Easy.

 

DELIMITER //
DROP PROCEDURE IF EXISTS `proc_FindStrInAllDB`//
# CALL `proc_FindStrInAllDB` ('testdb','中');
CREATE PROCEDURE `proc_FindStrInAllDB`
(
 IN p_dbname VARCHAR(128),
 IN p_finstr VARCHAR(128)
)
BEGIN
 -- Need to define variables that receive cursor data
 DECLARE tmp_dbname VARCHAR(128);
 DECLARE tmp_tbname VARCHAR(128);
 DECLARE tmp_colname VARCHAR(128);
 -- traverse the end of data flag
 DECLARE done INT DEFAULT FALSE;
  
   
 -- cursor
 DECLARE cur_db_tb CURSOR
 FOR
 SELECT  
  #*,
  C.table_schema,C.table_name,C.COLUMN_NAME
 FROM
  information_schema.`COLUMNS` C
  INNER JOIN information_schema.`TABLES` T ON C.`TABLE_NAME`=T.`TABLE_NAME`
 WHERE
  T.`TABLE_TYPE`='BASE TABLE'
 AND
  (C.data_type LIKE '%char%' OR C.data_type LIKE '%text%')
 AND
  (C.TABLE_SCHEMA=p_dbname OR IFNULL(p_dbname,'') ='') AND IFNULL(p_finstr,'')<>'';
  
 -- bind the end marker to the cursor
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
 CREATE TEMPORARY TABLE IF NOT EXISTS rstb(dbname VARCHAR(128),tbname VARCHAR(128),colname VARCHAR(128),cnt INT);
 -- open cursor
 OPEN cur_db_tb;
   -- start loop
   read_loop: LOOP
   -- Extract the data in the cursor, there is only one here, and the same is true for multiple;
   FETCH cur_db_tb INTO  tmp_dbname,tmp_tbname,tmp_colname;
   -- at the end of the statement
   IF done THEN
   LEAVE read_loop;
   END IF;
   -- here do what you want to do in the event loop
   SET @sqlstr=CONCAT('select count(1) into @rn from ',tmp_dbname,'.',tmp_tbname,' where ',tmp_colname,' like ''%',p_finstr,'%''');
   
   PREPARE str FROM @sqlstr;  
   EXECUTE str;   
   DEALLOCATE PREPARE str;
   IF IFNULL(@rn,0)>0
    THEN
    INSERT INTO rstb VALUES(tmp_dbname,tmp_tbname,tmp_colname,@rn);
   END IF;

   END LOOP;
 -- close cursor
 CLOSE cur_db_tb;
 
 SELECT * FROM rstb;
 DROP TABLE rstb;
 
END
//
DELIMITER ;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326528433&siteId=291194637