I have to add some enum options to a database table. The problem being, I will have to do this to several tables & databases, and they may not all have the same enum data type. Is there a why to write an alter table query or something similar to append options to a enum data type?
If there is no way to do this purely in MySQL, how would you approach this problem with a PHP开发者_如何学运维 script?
there is not easy way to append enum values.
this is ugly and untested, but i think it will give you an idea:
<?php
$sql = "select table_schema
, table_name
, column_name
, column_type
, is_nullable
, column_default
from information_schema
where data_type = 'enum'";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
// these are important --> leading comma --v close paren --v
$new_enum = substr($row['column_type', 0, -1) . ",'new','enums','here')"
$sql = "alter table `{$row['table_schema']}`.`{$row['table_name']}`";
$sql .= " modify column `{$row['column_name']}`";
$sql .= " $new_enum";
$sql .= ($row['is_nullable'] == 'YES') ? " NULL" : " NOT NULL";
$sql .= " default $row['column_default']";
mysql_query($sql);
}
you could probably do this "purely in mysql" with a stored procedure, but that's more than i can wrap my brain around right now. :)
精彩评论