Change column type without losing data
Asked Answered
M

4

30

I am working on an SQL Database, I have a column named "Price". When the database was created the column "Price" was set to NVARCHAR I need to change its type to decimal(18, 2) without losing the data in the database. This should be done by an SQL Script

I thought of creating a new column, moving the data to it, remove the old column, and then rename the newly created column.

Can someone help me with an example on how to do this? Also is there a function in SQL to Parse string to decimal?

Thanks

Mahau answered 11/6, 2012 at 9:48 Comment(1)
Have you done some research on how to do this? What have you got and where are you stuck?Iceblink
D
31

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.

Disclamation answered 11/6, 2012 at 9:51 Comment(3)
Missing step where you rename new_column_name to old_column_name, still +1Firestone
I got "Syntax error: unexpected 'decimal (decimal)'" on the convert() functionFlour
Sure wish mysql just did this for you :/ Seems like busy work. Thanks for answer!Tattan
P
4

Something Like

Alter Table [MyTable] Add 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

Paramnesia answered 11/6, 2012 at 12:17 Comment(0)
H
4

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.

Holm answered 10/4, 2018 at 5:46 Comment(0)
P
0

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..

Ptisan answered 11/6, 2012 at 9:54 Comment(1)
Note - how to find that : https://mcmap.net/q/500607/-generate-changes-scriptAvoidance

© 2022 - 2024 — McMap. All rights reserved.