小编典典

MySQL添加列(如果不存在)

mysql

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_NAME = 'email_subscription' AND COLUMN_NAME = 'subscribe_all')
  THEN 
  ALTER TABLE email_subscription
  ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
  ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;

我看了很多例子。但是此查询不起作用,出现以下错误:

错误1064(42000):您的SQL语法有错误;在第1行的’IF NOT EXISTS(SELECT * FROM
INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME
=’)附近,查看与您的MySQL服务器版本相对应的手册以使用正确的语法。


阅读 662

收藏
2020-05-17

共1个答案

小编典典

您可以为查询创建一个过程,

DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
    DECLARE _count INT;
    SET _count = (  SELECT COUNT(*) 
                    FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE   TABLE_NAME = 'email_subscription' AND 
                            COLUMN_NAME = 'subscribe_all');
    IF _count = 0 THEN
        ALTER TABLE email_subscription
            ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
            ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;
    END IF;
END $$
DELIMITER ;
2020-05-17