2014-08-29 44 views
0

我正在嘗試ALTER新列IF NOT EXITS。我修改的this question的第三個答案的代碼:SQL:ALTER新列IF NOT EXISTS - 如何?

DELIMITER $$ 

DROP PROCEDURE IF EXISTS myUpgrade $$ 
CREATE PROCEDURE myUpgrade() 
BEGIN 

IF NOT EXISTS 
    ((SELECT * FROM information_schema.COLUMNS WHERE `TABLE_SCHEMA` = DATABASE() AND`COLUMN_NAME` = 'myNewColumn' `TABLE_NAME` = 'my_table')) 
THEN 
    ALTER TABLE `my_table` ADD `myNewColumn` VARCHAR(255) NOT NULL AFTER `id`; 
ENDIF; 

END $$ 

CALL myUpgrade() $$ 

DELIMITER; 

錯誤

#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 '`TABLE_NAME` = 'my_table')) 
THEN 
    ALTER TABLE `my_table` ADD `myNewColumn` VA' at line 5 

或許有用:

  • 我運行在phpMyAdmin(4.0.10deb1)代碼
  • 服務器版本:5.5.38-0ubuntu0.14.04.1
  • 協議的版本:10
  • 的Apache/2.4.7
  • 數據庫,客戶端版本的libmysql - 38年5月5日
  • PHP的擴展:mysqli的

提前感謝!

+0

您在''myNewColumn'TABLE_NAME'之間缺少'AND'運算符 – rcdmk 2014-08-29 15:37:09

回答

1

你是WHERE子句中的TABLE_NAME條件之前缺少一個AND

IF NOT EXISTS 
    ((SELECT * FROM information_schema.COLUMNS 
     WHERE `TABLE_SCHEMA` = DATABASE() 
     AND `COLUMN_NAME` = 'myNewColumn' 
     AND `TABLE_NAME` = 'my_table')) 

而且,需要在END IF的空間。

1

我想你missinhg和 'myNewColumn' 和TABLE_NAME

這特定部分應該是這樣的:

((SELECT * FROM information_schema.columns在TABLE_SCHEMA = DATABASE()和COLUMN_NAME =' myNewColumn'ANDTABLE_NAME ='my_table'))