简体   繁体   English

用Underscore MySQL替换列名中的空格

[英]Replace Spaces in Column Name with Underscore MySQL

I have inherited a MySQL database that contains many columns in many tables that have spaces in their names. 我继承了一个MySQL数据库,该数据库包含许多表中的许多列,这些表的名称中有空格。 I have been asked to change all spaces in column names to underscores. 我被要求将列名中的所有空格更改为下划线。 Is there a way to do this with a script? 有没有办法用脚本做到这一点?

I thought that I can get them all listed with a SELECT from information_schema.... but I am not sure how to I can do the replacement. 我以为我可以通过information_schema中的SELECT列出它们。...但是我不确定该如何进行替换。

My logic would be that if the column name contains a space, replace it with an underscore. 我的逻辑是,如果列名包含空格,请用下划线替换。 But I am not sure how to do that. 但是我不确定该怎么做。

if you have the privileges, you would do the following: 如果您有特权,则可以执行以下操作:

UPDATE COLUMNS SET COLUMN_NAME = REPLACE(COLUMN_NAME, ' ', '_')

But most likely, you cant alter the schema. 但最有可能的是,您无法更改架构。

update information_schema.TABLES a
        join
    information_schema.COLUMNS b ON a.TABLE_Schema = b.TABLE_SCHEMA 
set 
    b.COLUMN_NAME = REPLACE(b.COLUMN_NAME, ' ', '_')
where
    a.TABLE_SCHEMA = 'YOURDBNAME'; 

Raheel Hasan's should be the right answer if you have the privileges for information_schema database. 如果您具有information_schema数据库的特权,那么Raheel Hasan的答案应该是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM