2017-09-02 64 views
0

運行存儲過程我已經創造了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 

回答

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 */ 
    
+0

它的工作原理,謝謝。 – oda356