简体   繁体   中英

How to change column data type without loosing data in Mysql

I have a city_id column which has varchar(255) and null values .I want to change it to big integer .

I will use:

ALTER TABLE Customer
ALTER COLUMN CITY_ID BIGINT

Do I loose or corrupt any data ?

You could try adding a new big integer column as an intermediate step:

-- add new column
ALTER TABLE Customer ADD COLUMN CITY_ID_NEW BIGINT;

-- populate new column
UPDATE Customer
SET CITY_ID_NEW = CAST(CITY_ID AS UNSIGNED);

-- drop old column and rename new column
ALTER TABLE Customer DROP COLUMN CITY_ID;
ALTER TABLE Customer CHANGE COLUMN CITY_ID_NEW CITY_ID BIGINT NULL DEFAULT NULL;

I assume above that your integer values are all positive, ie they are not signed. If you want signed integers, then change the cast in the update to SIGNED .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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