如何检查表中是否存在列,并根据结果执行操作

时间:2012-04-01 05:56:58

标签: mysql

我使用MySQL 5.5.16。

我正在尝试检查某个表中是否存在某个列。如果是,我想更新其type & collation,如果不是,我想将其添加到表格中。

我已阅读有关IF EXISTS声明的类似帖子HereHere。但是我的查询出错:

IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'e4s_account_details' AND column_name = 'accountID') THEN
   ALTER TABLE 'e4s_account_details' CHANGE 'accountID' 'accountID' INT(10) NOT NULL AUTO_INCREMENT;
ELSE 
   ALTER TABLE 'e4s_account_details' ADD COLUMN 'accountID' INT(10) NOT NULL AUTO_INCREMENT;
END IF;

我得到的错误是:

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 'IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'e4s_acco' at line 1

BTW,如果我只查询这个:

(SELECT * FROM information_schema.columns WHERE table_name = 'e4s_account_details' AND column_name = 'accountID');

我没有收到错误,并且返回了表+列信息。

1 个答案:

答案 0 :(得分:0)

您不能直接在select查询中使用此语法,而是可以使用stored procedure或查询information schema表来执行此操作。

相关问题