Reputation: 3745
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;
Upvotes: 4
Views: 2383
Reputation: 2032
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
Upvotes: 1