Skip to content

根据某条件批量修改表

L edited this page Jun 18, 2021 · 4 revisions

以下语句是为表名开头为qweerrty或者asddfgghh的表添加字段newColumnName,并将执行sql输出到指定目录

SELECT CONCAT('ALTER TABLE ', table_name, ' add column newColumnName varchar(50);')
  FROM information_schema.tables
  WHERE table_schema='mySchema'
  and (table_name like 'qweerrty%' or table_name like 'asddfgghh%')
  INTO OUTFILE 'outputFilePath';

然后拿到该文件,执行sql即可

Tips

报错

The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

原因是MySQL限制了导入导出目录权限
查询secure-file-priv的值

SHOW VARIABLES LIKE "secure_file_priv";

secure_file_priv为NULL,表示禁止。
secure_file_priv值有文件夹目录,则表示只允许该目录下文件。
secure_file_priv为空,则表示不限制目录。
解决方案
方案一:把导入文件放入secure-file-priv目前的value值对应路径即可。
方案二:把secure-file-priv的value值修改为准备导入文件的放置路径。
方案三:修改配置
去掉导入的目录限制。可修改mysql配置文件(Windows下为my.ini, Linux下的my.cnf),在[mysqld]下面,查看是否有:

secure_file_priv =

如上这样一行内容,如果没有,则手动添加。如果存在如下行:

secure_file_priv = /home 

这样一行内容,表示限制为/home文件夹。而如下行:

secure_file_priv =

这样一行内容,表示不限制目录,等号一定要有,否则mysql无法启动。
修改完配置文件后,重启mysql生效。

关闭:service mysqld stop
启动:service mysqld start

参考资料

search simple way to alter multi tables in one time in mysql
Mysql 导入文件提示 --secure-file-priv option 问题

Clone this wiki locally