How to convert MySQL field types?

三世轮回 提交于 2020-06-27 15:13:44

问题


I have already come across the convert function. As I understand it, the basic syntax is:

select convert(columnName, targetFieldType) as newColumnName from table;

Running this command doesn't give me any errors, but when I check the data types they are unchanged. Even when I use commit; the data remains unchanged. In particular, I'm trying to convert data with long type to varchar. Any ideas?


回答1:


The given SELECT query will return the value in the new type, but it doesn't change the field type of the table in your database.

If you want to permanently change the table on disk, use:

ALTER TABLE table CHANGE columnName newColumnName targetFieldType NOT NULL;

Note that for large tables, this can take a while, because MySQL rewrites the entire table.

Note: remove the NOT NULL qualifier if you also want to allow NULL values in this column.

For more information, see ALTER TABLE Syntax in MySQL Reference Manual.




回答2:


Note that you can convert anything to character type easily by using CONCAT:

select concat(columnName,'') as newColumnName from table;

The actual syntax you want for CONVERT is as follows:

select convert(columnName, char) as newColumnName from table;

There is no varchar type available to CONVERT or CAST, but casting to char without giving the field length should be the result you want.



来源:https://stackoverflow.com/questions/1742624/how-to-convert-mysql-field-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!