我想删除并创建一个在存储过程参数中传递名称的表。我写了以下存储过程。
CREATE DATABASE db1;
USE db1;
DROP PROCEDURE IF EXISTS drop_create;
DELIMITER $$
CREATE PROCEDURE drop_create(IN tbname VARCHAR(15))
BEGIN
SET @droptable = CONCAT ("DROP TABLE IF EXISTS ", tbname);
SET @createtable = CONCAT("CREATE TABLE ", tbname, " (c0 INT PRIMARY KEY, c1 VARCHAR(16000)" );
PREPARE deletetb FROM @droptable;
PREPARE createtb FROM @createtable ;
EXECUTE deletetb ;
EXECUTE createtb;
DEALLOCATE PREPARE createtb ;
DEALLOCATE PREPARE deletetb ;
END $$
DELIMITER ;
当我执行它时,我得到以下错误。
Call db1.drop_create('abd');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
显然,我无法在上面的SP中找到语法错误。我究竟做错了什么?问题必须出现在与CREATE TABLE相关的语句中,因为当我对第8,10,12和4行进行注释时13然后SP工作正常。我正在使用Mysql 5.6
答案 0 :(得分:2)
糟糕!以下语句中缺少右括号:
SET @createtable = CONCAT("CREATE TABLE ", tbname, " (c0 INT PRIMARY KEY, c1 VARCHAR(16000)" );
应该是:
SET @createtable = CONCAT("CREATE TABLE ", tbname, " (c0 INT PRIMARY KEY, c1 VARCHAR(16000))" );
^
答案 1 :(得分:0)
您的代码有很多错误。正在按如下方式进行更正。 VARCHAR不能假设1600.它可以是550周围。
DELIMITER $$
CREATE DATABASE db1;
USE db1;
DROP PROCEDURE IF EXISTS drop_create;
CREATE PROCEDURE drop_create(IN tbname VARCHAR(15))
BEGIN
SET @droptable = CONCAT ('DROP TABLE IF EXISTS ', tbname);
PREPARE deletetb FROM @droptable;
EXECUTE deletetb ;
DEALLOCATE PREPARE deletetb ;
SET @createtable = CONCAT('CREATE TABLE ', tbname, ' (c0 INT NOT NULL AUTO_INCREMENT, c1 VARCHAR(550),PRIMARY KEY(c0))ENGINE=InnoDB DEFAULT CHARSET=utf8');
PREPARE createtb FROM @createtable ;
EXECUTE createtb;
DEALLOCATE PREPARE createtb ;
END $$
DELIMITER ;
现在尝试。代码应该运行良好。