在 MySQL 中批量更改列类型 [英] bulk changing column types in MySQL

查看:34
本文介绍了在 MySQL 中批量更改列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 脚本,用户可以在其中创建问卷,以及数据库中的脚本表来存储传入的数据.该站点已经上线一段时间了,数据库中大约有 100 个表.

I have a PHP script where users create questionnaires, and the script tables in the DB to store the incoming data. The site's been live for a while, and there are about 100 tables in the database.

我的剧本有很大的缺陷!它在我真正需要文本"的地方调用小文本"字段.有没有办法将所有 tinytext 列批量更新为文本?

My script was awfully flawed! It calls for "tinytext" fields in places where I really need "text". Is there a way to bulk update all of the tinytext columns to text?

谢谢!

推荐答案

无需存储过程的解决方案(仅使用 phpMyAdmin 或任何其他 DBA 工具).

Solution without stored procedures (using only phpMyAdmin or any other DBA tool).

运行以下查询

SELECT 
    CONCAT('ALTER TABLE ',
            TABLE_NAME,
            ' CHANGE COLUMN ',
            COLUMN_NAME,
            ' ',
            column_name,
            ' TARGET_TYPE ',
            CASE
                WHEN IS_NULLABLE = 'NO' THEN ' NOT '
                ELSE ''
            END,
            ' NULL;') AS que
FROM
    information_schema.columns
WHERE
    table_schema = 'MY DB'
        AND data_type = 'SOURCE_TYPE';

此查询将返回所有要触发的语句.您可以运行它们或保存到 SQL 升级脚本中

This query will return you all the statements to fire. You can run them or save into a SQL Upgrade script

示例(从 tinyint 到 bit):

Example (from tinyint to bit):

ALTER TABLE mytable CHANGE COLUMN redacted redacted BIT  NULL;
ALTER TABLE mytable CHANGE COLUMN redacted2 redacted2 BIT NOT NULL;

这篇关于在 MySQL 中批量更改列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆