搜索多个模式以获得特定值

zxlwwiss  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(286)

我有一个具有多个模式的服务器。我需要找到特定的电子邮件地址。每个模式看起来几乎相同,它们具有相同的结构。我想做的是编写一个脚本来显示与给定电子邮件相关的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;
vlju58qv

vlju58qv1#

在你介绍之前,看起来你做得很好。
因为使用循环,所以while是多余的,所以应该删除这些行。
循环没有终点。
concat语句将第一次使用db\u name视为您的列名之一,这类名称存在一些引用问题。
“;”在过程的末尾应该是您指定为分隔符的“$$”。
我对您的变量名做了一些修改,但是这个整理过的版本应该可以说明这一点。

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 这将有助于你的程序结构。

相关问题