views:

448

answers:

2

Hi All, I am trying to create a table though prepare statement but it is giving me syntax error. well if o try to execute the same statement individually then it work fine.

here's my statement -

SET @Stmt1 = Concat('DROP TABLE IF EXISTS ',DB,'.`county`;\n'
'CREATE TABLE IF NOT EXISTS ',DB,'.`County`
(
  `CountyID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `CountyName` VARCHAR(45) NOT NULL,
  `CountyCode` VARCHAR(30) NOT NULL,
   PRIMARY KEY (`CountyID`)
)');

Prepare stmt2 From @stmt1;
Execute stmt2;

please can anyone tell me what m i missing in this statement? It is giving me an error on this line

'CREATE TABLE IF NOT EXISTS ',DB,'.`County`
(
  `CountyID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
A: 

are you not missing a comma between the two strings in the concat?

should be

SET @Stmt1 = Concat('DROP TABLE IF EXISTS ',DB,'.county;\n', 'CREATE TABLE IF NOT EXISTS ',DB,'.County ( CountyID INT UNSIGNED NOT NULL AUTO_INCREMENT, CountyName VARCHAR(45) NOT NULL, CountyCode VARCHAR(30) NOT NULL, PRIMARY KEY (CountyID) )');
Jonathan Fingland
Hi! It is still giving me same error.
MySQL DBA
is there any particular reason you're inserting a \n?
Jonathan Fingland
no its just that i wanted them on new line
MySQL DBA
I'm just suspicious that's it's being interpreted literally in this case
Jonathan Fingland
It's easy to confirm in the mysql client: select concat('abc', '\n', 'xyz'); Nope, the \n is translated into a newline.
Bill Karwin
+3  A: 

http://dev.mysql.com/doc/refman/5.1/en/prepare.html says:

The text [of the preparable statement] must represent a single SQL statement, not multiple statements.

So you'll have to execute your DROP TABLE statement first, and then prepare and execute the CREATE TABLE statement separately.

Bill Karwin