SQL:ALTER新列如果不是EXISTS - 如何?

时间:2014-08-29 13:45:34

标签: php mysql database mysqli

我正在尝试ALTER新列IF NOT EXITS。我修改了this question的第三个答案的代码:

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 - 5.5.38
  • PHP-Extension:mysqli

提前致谢!

2 个答案:

答案 0 :(得分:1)

您在AND条款中的TABLE_NAME条件之前错过了WHERE

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

此外,END IF中需要有一个空格。

答案 1 :(得分:1)

我认为你很想念他 ' myNewColumn'和TABLE_NAME

该特定部分应如下所示:

((SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE()和COLUMN_NAME =' myNewColumn' AND TABLE_NAME = ' MY_TABLE'))