简体   繁体   中英

Change database column name and its type without losing data

I want to change name and type of column from BIT(1) to INT(1) .

I am using MySQL Workbench.

I tried this:

ALTER TABLE table_name ADD new_column_name INT(1)

update table_name
set new_column_name = convert(INT(1), old_column_name)

ALTER TABLE table_name DROP COLUMN old_column_name

But I am getting this error

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'INT(1), old_column_name)'
ALTER TABLE table_name ADD new_column INT(1);

update table_name
  set new_column = case when old_column then 1 else 0 end;

ALTER TABLE table_name DROP COLUMN old_column;

or simply use:

ALTER TABLE table_name MODIFY COLUMN old_column int;
ALTER TABLE table_name CHANGE old_column_name new_col_name varchar(20) not null; 

I put varchar as an examaple. you can change to any data type you like. You can also add constraints after that.

Try something Like this.

ALTER TABLE table_name ADD new_column_name INT

update table_name
set new_column_name = convert(int,convert(varchar(1), old_column_name))

INT(1) doesn't seem to be a valid type for conversion.

Furthermore, the right syntax is CONVERT(<element>, <type>) .

You can find more in detail here .

ALTER TABLE table_name ALTER COLUMN creation_date TYPE timestamp USING creation_date::timestamp;

尝试这个

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