我在一台服务器上有几个客户端数据库。它们都有一个前缀。为此,让我们使用“piggy_”作为前缀。
IE
piggy_client_a
piggy_client_b
piggy_client_c
下面是三个小猪数据库的代码并添加了一堆用户。(用于检测):
CREATE SCHEMA IF NOT EXISTS piggy_client_a;
CREATE TABLE piggy_client_a.user (
id INT(11) NOT NULL AUTO_INCREMENT,
fullname VARCHAR(30) DEFAULT NULL,
email VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO piggy_client_a.user (fullname, email) VALUES
("chris davis", "[email protected]"),
("chris td", "[email protected]"),
("bob sinclair", "[email protected]"),
("frank sidebottom", "[email protected]");
CREATE SCHEMA IF NOT EXISTS piggy_client_b;
CREATE TABLE piggy_client_b.user (
id INT(11) NOT NULL AUTO_INCREMENT,
fullname VARCHAR(30) DEFAULT NULL,
email VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO piggy_client_b.user (fullname, email) VALUES
("fanny adams", "[email protected]"),
("colin furry", "[email protected]"),
("chris grumps", "[email protected]"),
("tracey singer", "[email protected]");
CREATE SCHEMA IF NOT EXISTS piggy_client_c;
CREATE TABLE piggy_client_c.user (
id INT(11) NOT NULL AUTO_INCREMENT,
fullname VARCHAR(30) DEFAULT NULL,
email VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO piggy_client_c.user (fullname, email)VALUES
("mary qos", "[email protected]"),
("curtis jackson", "[email protected]"),
("christine motor", "[email protected]"),
("tom peters", "[email protected]");
每个 piggy 数据库中都有相同的模式。其中一个表是user
,我想找到用户所在的任何这些数据库。
我写了一个存储过程,总体上它可以工作。然而,它只处理第一个小猪数据库。我已经仔细检查过,如果我将特定用户添加到piggy_client_c
数据库中,它不会被返回。
这是我的代码:
DELIMITER $$
DROP PROCEDURE IF EXISTS `find_user`$$
CREATE PROCEDURE `find_user`(IN partial_name VARCHAR(20))
BEGIN
DECLARE database_name VARCHAR(128) DEFAULT '';
DECLARE non_found INTEGER DEFAULT 0;
DECLARE database_list
CURSOR FOR
SELECT SCHEMA_NAME FROM information_schema.SCHEMATA
WHERE SCHEMA_NAME LIKE `piggy_client_%`
ORDER BY SCHEMA_NAME ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET non_found = 1;
OPEN database_list;
check_table: LOOP
FETCH database_list INTO database_name;
IF non_found = 1 THEN
LEAVE check_table;
END IF;
SET @sql = CONCAT('SELECT "',database_name,'" AS db_name, fullname,email FROM ',database_name,'.user WHERE trim(fullname) like "%',partial_name,'%"');
PREPARE db_statement FROM @sql;
EXECUTE db_statement;
DEALLOCATE PREPARE db_statement;
END LOOP check_table;
CLOSE database_list;
END$$
DELIMITER ;
我看不到任何会导致函数退出或不循环光标的东西,但我对此相当陌生。
或者,如果我可以“单步执行”代码,那将很有用,或者输出调试信息。
TIA,克里斯