MYSQL - set default as NULL to all columns, where default is not set

前端 未结 2 948
迷失自我
迷失自我 2021-01-25 05:45

I have about 12 databases, each with 50 tables and most of them with 30+ columns; the db was running in strict mode as OFF, but now we had to migrate the db to cleardb service w

相关标签:
2条回答
  • 2021-01-25 06:14

    You should consider using the information_schema tables to generate DDL statements to alter the tables. This kind of query will get you the list of offending columns.

    SELECT CONCAT_WS('.',TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME) col  
      FROM information_schema.COLUMNS
     WHERE IS_NULLABLE = 0
       AND LENGTH(COLUMN_DEFAULT) = 0 
       AND TABLE_SCHEMA IN ('db1', 'db2', 'db3')
    

    You can do similar things to generate ALTER statements to change the tables. But beware, MySQL likes to rewrite tables when you alter certain things. It might take time.

    DO NOT attempt to UPDATE the information_schema directly!

    You could try changing the strict_mode setting when you connect to the SaaS service, so your software will work compatibly.

    This is a large project and is probably important business for cleardb. Why not ask them for help in changing the strict_mode setting?

    0 讨论(0)
  • 2021-01-25 06:19

    This is what I came up with on the base of @Ollie-jones script

    https://gist.github.com/brijrajsingh/efd3c273440dfebcb99a62119af2ecd5

    SELECT CONCAT_WS('.',TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME) col,CONCAT('alter table ',TABLE_NAME,' MODIFY COLUMN ', COLUMN_NAME,' ',DATA_TYPE,'(',CHARACTER_MAXIMUM_LENGTH,') NULL DEFAULT NULL') as script_col
      FROM information_schema.COLUMNS
     WHERE is_nullable=0 
     and length(COLUMN_DEFAULT) is NULL and
     CHARACTER_MAXIMUM_LENGTH is not NULL and 
     table_schema = 'immh' 
     Union
     SELECT CONCAT_WS('.',TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME) col,CONCAT('alter table ',TABLE_NAME,' MODIFY COLUMN ', COLUMN_NAME,' ',DATA_TYPE,' NULL DEFAULT NULL') as script_col
      FROM information_schema.COLUMNS
     WHERE is_nullable=0 
     and length(COLUMN_DEFAULT) is NULL and
     CHARACTER_MAXIMUM_LENGTH is NULL and 
     table_schema = 'immh' 
    
    0 讨论(0)
提交回复
热议问题