您可以借助 INFORMATION_SCHEMA.COLUMNS 来实现此目的。语法如下 –
SELECT CONCAT('ALTER TABLE ', TABLE_NAME, ' CHANGE `', COLUMN_NAME, '` `', LOWER(COLUMN_NAME), '` ', COLUMN_TYPE, ';') AS anyAliasName FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ‘yourDatabaseName’;
现在使用有两个表的数据库。数据库名称如下“bothinnodbandmyisam”。该数据库有以下表格 –
- employee
- student
employee 表的描述是如下 –
mysql> desc employee;
以下是输出。假设员工表中有以下列不是小写的 –
+--------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | EmployeeId | int(11) | YES | | NULL | | | EmployeeName | varchar(30) | YES | | NULL | | +--------------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
学生表的说明如下。查询如下 –
mysql> desc student;
以下是输出。假设学生表中有以下列不是小写的 –
+-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | StudentId | int(11) | YES | | NULL | | | StudentName | varchar(20) | YES | | NULL | | +-------------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
这是将所有表的列名更改为小写的查询。查询如下 –
mysql> SELECT CONCAT('ALTER TABLE ', TABLE_NAME, ' CHANGE `', COLUMN_NAME, '` `', -> LOWER(COLUMN_NAME), '` ', COLUMN_TYPE, ';') AS changeColumnNameToLower -> FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'bothinnodbandmyisam';
以下是显示 ALTER TABLE 命令的输出,其中显示了更新的列名称 –
+------------------------------------------------------------------------+ | changeColumnNameToLower | +------------------------------------------------------------------------+ | ALTER TABLE employee CHANGE `EmployeeId` `employeeid` int(11); | | ALTER TABLE employee CHANGE `EmployeeName` `employeename` varchar(30); | | ALTER TABLE student CHANGE `StudentId` `studentid` int(11); | | ALTER TABLE student CHANGE `StudentName` `studentname` varchar(20); | +------------------------------------------------------------------------+ 4 rows in set (0.00 sec)
查看上面的示例输出,所有列名称都已更改为小写。