使用变量在SELECT语句中引用另一个数据库

时间:2017-08-01 13:09:31

标签: mysql variables stored-procedures

我试图遍历表中包含另一个数据库的数据库名称的所有行。这就是我所拥有的编译但不起作用的东西,因为MySQL采用了数据库' bit作为实际的数据库名称而不是内容。

如何更改以下内容以使其获取变量的内容?

DROP PROCEDURE IF EXISTS CYCLE;
DELIMITER ;;
CREATE PROCEDURE CYCLE()
BEGIN
  DECLARE data_name CHAR(255);
  DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT database FROM company;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO database;
    IF done THEN
      LEAVE read_loop;
    END IF;
    SELECT * FROM database.table LIMIT 1;
  END LOOP;
  CLOSE cursor_i;
END;
;;
DELIMITER ;

更新:要明确我知道'数据库'是一个保留字。我在这里用它来代替我用过的实际变量名。

1 个答案:

答案 0 :(得分:0)

您无法在表select语句中评估变量的内容,在这种情况下,您必须在字符串中构建一个执行查询:

DROP PROCEDURE IF EXISTS CYCLE;
DELIMITER ;;
CREATE PROCEDURE CYCLE()
BEGIN
  DECLARE data_name CHAR(255); -- unused?
  DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT database_name FROM company;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO data_name;
    IF done THEN
      LEAVE read_loop;
    END IF;
    -- now build the query before execute:
    set @sql = concat('SELECT * FROM `',data_name,'`.`your_table` LIMIT 1');

    -- and execute
    prepare stmt  from @sql;
    execute stmt;
    deallocate prepare stmt ;

  END LOOP;
  CLOSE cursor_i;
END;
;;
DELIMITER ;

*最好不要使用导致更多问题的变量名来混淆我们。 #JustSaying