我正在尝试编写一个包装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 ;
答案 0 :(得分:2)
你不能像这样传递表名,但你可以像这样使用prepare语句 -
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 ;