简体   繁体   中英

Alter table column datatype

I want to alter the type of a column from TIME datatype to a SMALL int in number of second since midnight without changing the name.

I have a select statement that makes this change, but I'm wondering if there is a way to change the datatype directly without creating temporary fields.

select ROUND(convert(begin_time, UNSIGNED)/100) % 100 +
       60 * ROUND(convert(begin_time, UNSIGNED)/10000) from time_window;

I don't think you can change the schema and the data in one stroke like that. That's not to say you can't do it atomically -- you can use a transaction for that depending on your storage engine. But you're going to have to do this in steps.

1) Change the old column's name.

ALTER TABLE time_window CHANGE COLUMN begin_time begin_time_old TIME;

2) Add a new column of type SMALL with the column's old name to store the new data.

ALTER TABLE time_window ADD COLUMN begin_time SMALL;

3) Insert the data using your conversion.

UPDATE time_window 
SET begin_time = ROUND(convert(begin_time_old, UNSIGNED)/100) % 100 +
60 * ROUND(convert(begin_time_old, UNSIGNED)/10000)

4) Drop the old column.

ALTER TABLE time_window DROP COLUMN begin_time_old

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