2

I want to drop and create a table with name passed in the stored procedure argument. I've written following stored procedure.

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 ;

When I execute it, I get following error.

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

Apparently, I am not able to find the syntax error in SP above. What am I doing wrong? Problem must be in CREATE TABLE related statements because when I comment line#8, 10, 12 & 13 then SP works fine. I am using Mysql 5.6

2 Answers 2

2

Oops! a closing brace was missing in the following statement:

SET @createtable = CONCAT("CREATE TABLE ", tbname, " (c0 INT PRIMARY KEY, c1 VARCHAR(16000)" );

It should be:

SET @createtable = CONCAT("CREATE TABLE ", tbname, " (c0 INT PRIMARY KEY, c1 VARCHAR(16000))" );
                                                                                           ^
Sign up to request clarification or add additional context in comments.

Comments

0

Your code has many errors .it is being corrected as follows. VARCHAR cannot asume 1600.It can be arround 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 ;

NOW try.The code should works well.

3 Comments

VARCHAR can be up to 65535 bytes in MySQL. See The CHAR and VARCHAR types.
Thank you Mr.Bill Kanwin for being isolated a useful addition.
Thank you Mr.Bill Karwin for being isolated a useful addition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.