如果存在于mysql中,如何删除列?

时间:2016-09-28 05:18:54

标签: mysql sql alter

ALTER TABLE user DROP COLUMN registered_date

我们可以使用上面的命令删除一列。但是,如果列registered_date存在,我怎么能放弃呢?

1 个答案:

答案 0 :(得分:-1)

IF EXISTS(SELECT * 
          FROM information_schema.COLUMNS 
          WHERE 
          TABLE_SCHEMA = 'db_name' 
          AND TABLE_NAME = 'table_name' 
          AND COLUMN_NAME = 'column_name')
BEGIN
 ALTER TABLE table_name DROP COLUMN column_name
END

IF (SELECT COUNT(*) 
          FROM information_schema.COLUMNS 
          WHERE 
          TABLE_SCHEMA = 'db_name' 
          AND TABLE_NAME = 'table_name' 
          AND COLUMN_NAME = 'column_name'>0)
BEGIN
 ALTER TABLE table_name DROP COLUMN column_name
END