How to move columns in a MySQL table?

后端 未结 4 904
孤街浪徒
孤街浪徒 2020-11-29 16:04

Currently I am having the following MySQL table: Employees (empID, empName, department);

I want to change the table to the following: Employees (e

4条回答
  •  伪装坚强ぢ
    2020-11-29 17:00

    I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

    SET @NeighboringColumn = '';
    
    SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
    `",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
    NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
    `",@NeighboringColumn,"`;")
    FROM information_schema.COLUMNS c, information_schema.TABLES t
    WHERE c.TABLE_SCHEMA = ''
    AND c.COLUMN_NAME = ''
    AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
    AND c.TABLE_NAME = t.TABLE_NAME
    AND t.TABLE_TYPE = 'BASE TABLE'
    AND @NeighboringColumn IN (SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS c2 
        WHERE c2.TABLE_NAME = t.TABLE_NAME);
    

提交回复
热议问题