sql ALTER TABLE if列不存在。来自http://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql ALTER TABLE if列不存在。来自http://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not相关的知识,希望对你有一定的参考价值。

SET @preparedStatement = (SELECT IF(
    (SELECT DATA_TYPE
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_schema = 'db_name'
        AND table_name = 'table_name'
        AND column_name = 'column_name'
    ) != 'int',
    "ALTER TABLE `tableName` MODIFY `colName` INT UNSIGNED;",
    "SELECT 1;"
));
PREPARE alterIfNotInt FROM @preparedStatement;
EXECUTE alterIfNotInt;

DEALLOCATE PREPARE alterIfNotInt;
SET @preparedStatement = (SELECT IF(
    (SELECT count(*)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_schema = 'db_name'
        AND table_name = 'table_name'
        AND column_name = 'column_name'
    ) > 0,
    "SELECT 1;",
    "ALTER TABLE `tableName` ADD `colName` TINYINT(1) NULL DEFAULT '0';"
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;

DEALLOCATE PREPARE alterIfNotExists;

以上是关于sql ALTER TABLE if列不存在。来自http://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not的主要内容,如果未能解决你的问题,请参考以下文章

ALTER TABLE CREATE CONSTRAINT IF NOT EXIST 可能吗?

列不存在 Laravel 工厂

Postgres 列不存在

sql [ALTER TABLE]要(1)添加,删除或修改列,或(2)在现有表中添加和删除各种约束。 #Syntax #Alter_table

sql [ALTER TABLE ADD COLUMN]将新列添加到现有表#SQL

SQL ALTER TABLE 语句