MySQL-在多个模式中搜索特定值

时间:2018-09-06 09:20:45

标签: mysql

我有一台具有多个架构的服务器。我需要找到特定的电子邮件地址。每个模式看起来都差不多,它们具有相同的结构。我想要做的是编写一个脚本,以显示与给定电子邮件相关的dbname和specyfic数据。这是我的脚本,但是不起作用:(

DELIMITER $$

#Drop procedure if exists SearchAllDb $$
Create procedure SearchAllDb()

BEGIN
DECLARE DB_NAME Varchar(50);
DECLARE done INT default FALSE;
DECLARE CURSOR_ALL_DB_NAMES CURSOR FOR
SELECT schema_name from information_schema.schemata
WHERE schema_name like 'itools_%';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN CURSOR_ALL_DB_NAMES;

myloop: LOOP
FETCH CURSOR_ALL_DB_NAMES INTO DB_NAME; 

IF done THEN LEAVE myloop;
END IF; 

WHILE done != TRUE DO

SET @SQL = CONCAT('select DB_NAME, id, sn, name, email 
from',DB_NAME,'.`open_cases` where email like 'xxx@yahoo.com'');
prepare stmt from @SQL;
execute stmt;
deallocate prepare stmt;

END WHILE; 

CLOSE CURSOR_ALL_DB_NAMES; 
END;

DELIMITER ;

我有一些类似的用t-sql编写的内容,并且可以正常工作...

DECLARE @DB_NAME VARCHAR(50);
DECLARE CURSOR_ALL_DB_NAMES CURSOR FOR
SELECT name FROM master.sys.databases
WHERE name like 'pickup-%' and name!= 'pickup-stored';

OPEN CURSOR_ALL_DB_NAMES;
FETCH NEXT FROM CURSOR_ALL_DB_NAMES INTO @DB_NAME 

WHILE @@Fetch_Status = 0
BEGIN
Print @DB_NAME;
exec ('select '''+ @DB_NAME + ''' as db, id, sn, email from ['+ 
@DB_NAME+'].dbo.requests where email in (''xxx@live.com'')');

FETCH NEXT FROM CURSOR_ALL_DB_NAMES INTO @DB_NAME 
END

CLOSE CURSOR_ALL_DB_NAMES;
DEALLOCATE CURSOR_ALL_DB_NAMES;

1 个答案:

答案 0 :(得分:0)

在您介绍WHILE之前,您似乎做得很好。

  1. 由于您正在使用LOOP,因此WHILE是多余的,应删除这些行。
  2. LOOP没有结束。
  3. CONCAT语句会将DB_NAME的首次使用视为您的列名之一,并且LIKE存在一些引用问题。
  4. ';'该过程的末尾应为您指定为DELIMITER的“ $$”。

我为您的变量名取了一些自由,但是经过整理的版本应该可以说明要点。

DELIMITER $$

DROP PROCEDURE IF EXISTS SearchAllDb $$
CREATE PROCEDURE SearchAllDb()
BEGIN
  DECLARE db_name VARCHAR(64);
  DECLARE done INT DEFAULT FALSE;
  DECLARE cur CURSOR FOR
    SELECT schema_name 
    FROM information_schema.schemata
    WHERE schema_name LIKE 'itools_%';

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur;

  myloop: LOOP
    FETCH cur INTO db_name; 

    IF done THEN 
      LEAVE myloop;
    END IF; 

    SET @SQL = CONCAT('SELECT ''', db_name, ''', id, sn, name, email 
      FROM `', db_name,'`.`open_cases` 
      WHERE email LIKE ''xxx@yahoo.com''');

    PREPARE stmt FROM @SQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

  END LOOP; 

  CLOSE cur; 
END $$

DELIMITER ;

https://dev.mysql.com/doc/refman/5.7/en/cursors.html文档中有一个很好的CURSOR示例,它将帮助您确定过程的结构。