如果列已经存在,则无法添加列?

时间:2015-08-17 10:27:08

标签: mysql sql alter-table

我正在尝试编写一个查询,以便在MySql表中添加一个列,如果它不存在,如下所示,但我收到的语法错误为:

  

SQL错误(1064):您的SQL语法中有错误;

     

检查与您的MySQL服务器版本相对应的手册,以便使用“#NOT NOT EXISTS附近使用的正确语法”(SELECT NULL           来自INFORMATION_SCHEMA.COLUMNS           WHE'在第1行。

查询:

 IF NOT EXISTS(SELECT NULL 
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE  table_name = 'Devicebattery'
        AND table_schema = 'mat'
        AND column_name = 'WrittenToServerDatabaseTimestamp')  
THEN
  ALTER TABLE 'Devicebattery' ADD 'WrittenToServerDatabaseTimestamp'
    TIMESTAMP(3) NOT NULL DEFAULT '1970-01-01 00:00:01.000';
END IF;

表格详情如下: -

CREATE TABLE Devicebattery (
    DeviceBatteryID INT(11) NOT NULL AUTO_INCREMENT,
    ByDevSessionId INT(11) NOT NULL,
    ByPatientId INT(11) NULL DEFAULT NULL,
    ByDeviceId INT(11) NULL DEFAULT NULL,
    Value FLOAT NULL DEFAULT NULL,
    SequenceId INT(11) NULL DEFAULT NULL,
    SyncStatus INT(11) NULL DEFAULT '0',
    Timestamp TIMESTAMP(3) NULL DEFAULT NULL,
    PRIMARY KEY (DeviceBatteryID),
    INDEX `ByDevSessionId` (ByDevSessionId),
    CONSTRAINT Devicebattery_ibfk_1 FOREIGN KEY (ByDevSessionId)
     REFERENCES devicesession (DeviceSessionID) ON UPDATE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=524994
;

2 个答案:

答案 0 :(得分:2)

在MYSQL中,IF ELSE逻辑应该是存储过程或用户定义函数的一部分。如果要动态添加列

,则应将其设置为存储过程
Create procedure add_column
as
Begin
IF NOT EXISTS(SELECT NULL 
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE  table_name = 'Devicebattery'
        AND table_schema = 'mat'
        AND column_name = 'WrittenToServerDatabaseTimestamp')  
THEN
  ALTER TABLE 'Devicebattery' ADD 'WrittenToServerDatabaseTimestamp' 
  TIMESTAMP(3) NOT NULL DEFAULT '1970-01-01 00:00:01.000';
END IF;
end

答案 1 :(得分:1)

尝试:

DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
  DECLARE _count INT;
  SET _count = (SELECT NULL 
         FROM INFORMATION_SCHEMA.COLUMNS
         WHERE  table_name = 'Devicebattery'
         AND table_schema = 'mat'
         AND column_name = 'WrittenToServerDatabaseTimestamp');
  IF _count = 0 THEN
    ALTER TABLE Devicebattery
        ADD COLUMN 'WrittenToServerDatabaseTimestamp' 
        TIMESTAMP(3) NOT NULL DEFAULT '1970-01-01 00:00:01.000';
  END IF;
END $$
DELIMITER ;

如果我了解您的需要,您也可以尝试使用@ Madhivanan的解决方案,然后这两个程序都应该有效。