DELIMITER // DROP PROCEDURE IF EXISTS `proc_FindStrInAllDataBase`// # CALL `proc_FindStrInAllDataBase` ('testdb','中'); CREATE PROCEDURE `proc_FindStrInAllDataBase` ( IN para_databasename VARCHAR(128), IN para_finstr VARCHAR(128) ) BEGIN -- 須要定義接收遊標數據的變量 DECLARE tmp_dbname VARCHAR(128); DECLARE tmp_tbname VARCHAR(128); DECLARE tmp_colname VARCHAR(128); -- 遍歷數據結束標誌 DECLARE done INT DEFAULT FALSE; -- 遊標 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=para_databasename OR IFNULL(para_databasename,'') ='') AND IFNULL(para_finstr,'')<>''; -- 將結束標誌綁定到遊標 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 cur_db_tb; -- 開始循環 read_loop: LOOP -- 提取遊標裏的數據,這裏只有一個,多個的話也同樣; FETCH cur_db_tb INTO tmp_dbname,tmp_tbname,tmp_colname; -- 聲明結束的時候 IF done THEN LEAVE read_loop; END IF; -- 這裏作你想作的循環的事件 SET @sqlstr=CONCAT('select count(1) into @rn from ',tmp_dbname,'.',tmp_tbname,' where ',tmp_colname,' like ''%',para_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 cur_db_tb; SELECT * FROM rstb; DROP TABLE rstb; END // DELIMITER ;