2

我正在尝试编写一个包含 SHOW CREATE TABLE 的存储过程。我的最终目标是从 information_schema 中动态查找模式名称并运行 SHOW CREATE TABLE schema.tableName。

似乎我无法在存储过程中运行 SHOW CREATE TABLE 。

DELIMITER $$
DROP PROCEDURE IF EXISTS ct$$
CREATE PROCEDURE ct (tableName VARCHAR(50))
BEGIN

  SHOW CREATE TABLE tableName;

END$$
DELIMITER ;


mysql> CALL ct('users');
ERROR 1146 (42S02): Table 'adcentraldb.tableName' doesn't exist
mysql> 

对于那些感兴趣的人,这就是我对正在工作的 SHOW CREATE TABLE 包装器的最终结果

DELIMITER $$
DROP PROCEDURE IF EXISTS ct$$

-- Wraps around SHOW CREATE TABLE.  Look at other schemas other than current.
CREATE PROCEDURE ct (tableName VARCHAR(50))
BEGIN
  DECLARE dbName VARCHAR(50);

  SET dbName = (SELECT `TABLE_SCHEMA` FROM `INFORMATION_SCHEMA`.`TABLES` 
  WHERE `TABLE_NAME` = tableName LIMIT 1);

  SET @a=CONCAT("SHOW CREATE TABLE ", dbName, '.', tableName);
  PREPARE stmt1 FROM @a;
  EXECUTE stmt1; 
  DEALLOCATE PREPARE stmt1;

END$$
DELIMITER ;
4

1 回答 1

2

您不能像这样传递表名,但您可以为此目的使用准备语句 -

DELIMITER $$
DROP PROCEDURE IF EXISTS ct$$
CREATE PROCEDURE ct (tableName VARCHAR(50))
BEGIN

  set @a=concat("SHOW CREATE TABLE ",tableName);
  PREPARE stmt1 FROM @a;
  EXECUTE stmt1; 
  DEALLOCATE PREPARE stmt1;

END$$
DELIMITER ;
于 2012-04-13T06:03:10.233 回答