在工作台中运行存储过程的错误

时间:2017-09-02 08:23:39

标签: mysql stored-procedures

我在MySQL工作台中创建了一个存储过程,如下所示,当我使用

use stock_data;
call CreateStockTable;

命令调用此过程,它发生错误:

16:09:29    call CreateStockTable   Error Code: 1064. 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 8    0.016 sec

我想创建名称以data_60 / data_00开头的表,我写了两个while语句来做到这一点。代码有什么问题?感谢。

CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateStockTable`()
BEGIN
DECLARE i int;     
DECLARE createSql VARCHAR(2560); 
DECLARE createIndexSql1 VARCHAR(2560);
DECLARE stockNum VARCHAR(4); 

set i=0; 
WHILE  (i< 3000) DO                     

      IF (i=0) THEN
      set stockNum='0000';
      ELSEIF (i<10) THEN
      set stockNum=CONCAT('000',i);
      ELSEIF (i<100) THEN
      set stockNum=CONCAT('00',i);
      ELSEIF (i<1000) THEN
      set stockNum=CONCAT('0',i);
      ELSE
      set stockNum=CONCAT('',i);
      END IF;

      SET createSql = CONCAT('CREATE TABLE IF NOT EXISTS data_00',stockNum,'(
      id int(11) AUTO_INCREMENT,
      date varchar(30),stock_code varchar(10),
      name varchar(20),P_close double,
      P_high double,P_low double,
      P_open double,P_percent double,
      volume int(11),turnover double,
      PRIMARY KEY (id,date)'
      ); 
      prepare stmt from @createSql; 
      execute stmt;                             
      SET i= i+1; 
END WHILE;

set i=0; 
WHILE  (i< 4000) DO                     
      IF (i=0) THEN
      set stockNum='0000';
      ELSEIF (i<10) THEN
      set stockNum=CONCAT('000',i);
      ELSEIF (i<100) THEN
      set stockNum=CONCAT('00',i);
      ELSEIF (i<1000) THEN
      set stockNum=CONCAT('0',i);
      ELSE
      set stockNum=CONCAT('',i);
      END IF;

      SET createSql = CONCAT('CREATE TABLE IF NOT EXISTS data_60',stockNum,'(
      id int(11) AUTO_INCREMENT,
      date varchar(30),stock_code varchar(10),
      name varchar(20),P_close double,
      P_high double,P_low double,
      P_open double,P_percent double,
      volume int(11),turnover double,
      PRIMARY KEY (id,date)'
      ); 
      prepare stmt from @createSql; 
      execute stmt;                             
      SET i= i+1; 
END WHILE;
END

1 个答案:

答案 0 :(得分:0)

您有一些错误:

  1. 您必须在使用之前设置本地变量@createSql

      SET @createSql = CONCAT('CREATE TABLE IF NOT EXISTS data_00',stockNum,'(
      id int(11) AUTO_INCREMENT,
      date varchar(30),stock_code varchar(10),
      name varchar(20),P_close double,
      P_high double,P_low double,
      P_open double,P_percent double,
      volume int(11),turnover double,
      PRIMARY KEY (id,date))'  /*add extra ) to fix create sql*/
      ); 
    

    您正在使用声明的变量createSql,但它不起作用。

  2. 您必须取消分配准备好的声明:

     prepare stmt from @createSql; 
     execute stmt;
     deallocate prepare stmt;  /*<--  free used resources */