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
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=>
I already test this on SQL server 2012 and its work.
You don't need to add a new column two times, just remove the old one after updating the new one:
Note that if the
old_column_name
is not numeric, theconvert
may fail.Something Like
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