Change column type without losing data

限于喜欢 提交于 2019-12-02 22:28:14

You don't need to add a new column two times, just remove the old one after updating the new one:

ALTER TABLE table_name ADD new_column_name decimal(18,2)

update table_name
set new_column_name = convert(decimal(18,2), old_column_name)

ALTER TABLE table_name DROP COLUMN old_column_name

Note that if the old_column_name is not numeric, the convert may fail.

Tony Hopkinson

Something Like

Alter Table [MyTable] Add Column NewPrice decimal(18,2) null

Then

Update [MyTable] Set NewPrice = Convert(decimal(18,2),[Price]) Where Price is not null

If the above fails then you'll need to beef it up to deal with the funnies

Once you are happy drop the old column with an Alter Table and rename the new one with sp_rename

You can make those changes visually using Management Studio. Then, use the button "Generate Change Script" to get the script for the changes you made. Be sure to do all testing in a copy of the original ddbb, in case something goes wrong..

If you just want to change only column's data type, you can do like this=>

Alter Table YourTableName
Alter Column ColumnName DataType 

I already test this on SQL server 2012 and its work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!