Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve data when changing column datatypes in MySQL?

Tags:

types

sql

mysql

For example, suppose I have a TINYINT column that I want to change into an ENUM. Is it possible to write a MySQL query that changes the datatype of the column while mapping the existing data so that (for example) 0 becomes No, 1 becomes Yes, and 2 becomes Maybe?

like image 694
DLH Avatar asked Aug 23 '10 13:08

DLH


3 Answers

I'm not sure if this is possible in MySQL, but an alternative solution would be to:

  1. Add the new column with the new type with a new name
  2. Set the new column values (given the old column values)
  3. Drop the old column
  4. Rename the new column to have the same name as the old column
like image 141
stark Avatar answered Nov 09 '22 07:11

stark


create the new column next to the old column, use an update to move the data over, then delete the original column.

like image 33
SorcyCat Avatar answered Nov 09 '22 07:11

SorcyCat


This needs a sequence of 4 steps- add new column, set data in new column, drop old column, rename new column

Use [Databasename]
Go
ALTER table [tableName]
Add [newColumnname] datatype
GO
Update [tableName] SET [newColumnname] = [oldColumnname]
GO
ALTER table [tableName] Drop Column [oldColumnname]
GO
EXEC sp_RENAME 'tableName.newColumnname' , 'oldColumnname', 'COLUMN'
GO
like image 1
AmbujMondal Avatar answered Nov 09 '22 08:11

AmbujMondal