Question

Is there a way I can set the default value to be 0 where a column matches certain criteria? Such as not having a default value or being varchar or INT?

It seems I have a table of about 100 columns (...) and I don't want to go through each one and set a default value.

This is just a testing machine and it seems to have something to do with the newer version of mysql I installed.

thanks!

Était-ce utile?

La solution

You could examine the INFORMATION_SCHEMA to generate a series of ALTER TABLE statements:

For example, choosing columns that currently have no default, from a given database & table:

SELECT CONCAT('ALTER TABLE `', TABLE_NAME, 
  '` ALTER COLUMN `', COLUMN_NAME, '` SET DEFAULT = 0;') AS _sql 
FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_DEFAULT IS NULL
 AND (TABLE_SCHEMA, TABLE_NAME) = ('mydatabase', 'mytable');

You can change the conditions based on other attributes of the column, e.g. data type, etc.

Autres conseils

No.

The default value for a column is an attribute of the schema and can't be changed based on the data that are in it. In other words, you can't combine SELECT statements with ALTER TABLE statements.

The closest you could come to it would be to use Perl or some other scripting language to dynamically generate the ALTER TABLE statements for you. Then you could apply those statements to your database.

Something like (pseudo-code):

@columns = "describe table_name";
for each $column in @columns {
    if (conditions are right){
        print "ALTER TABLE CHANGE COLUMN $column $column int default 0"
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top