Change column type without losing data - sql

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

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

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.

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

Related

How do I change a column data type from varchar(255) to date?

I am using a reporting database which consists of 20 tables on SQL Server. In marketing table I have a column report_date which is currently a varchar(255). It is basically a date formatted in a way 2017-12-12. I want to change the type of this column to a date. I’m running this script but getting errors. The script is down below:
USE [reporting].[dbo].[marketing]
GO
SELECT CONVERT(date, 'report_date');
These are the errors I’m getting.
Msg 911, Level 16, State 1, Line 1
Database 'dbo' does not exist. Make sure that the name is entered correctly.
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
How should I adjust the script?
If you want to change the column's data type (and you should) then you need to use an alter table statement. Your first error message is because of the USE directive - it should be
USE [reporting]
GO
Your second error message is because 'report_date' is a string constant, not a column name.
The select statement should be
SELECT CAST(report_date as date) -- Don't use Convert without the style argument....
FROM [dbo].[marketing]
Note that if you have even a single value that can't be converted to date you will get the second error again.
Basically I would recommend first making sure that the select statement completes without any exceptions, and only then alter the table:
USE reporting
GO
ALTER TABLE [dbo].[marketing]
ALTER COLUMN report_date DATE
GO
TRY THIS:
SELECT CONVERT(DATE, report_date) --If only for comparison
ALTER TABLE marketing ALTER COLUMN report_date DATE --If want to change in the table
The proper way to do this is like;
ALTER TABLE reportin.dbo.marketing ALTER COLUMN 'report_date' date
And you can check this How do you change the datatype of a column in MS SQL?
"Convert" is used for conversion from one datatype to other in select queries, you need to use alter statement for altering database columns and also
USE [databasename] is enough, so rewriting your query here :
USE [reporting]
GO
ALTER TABLE marketing ALTER COLUMN ReportDate DATE
Slow, but safe way is to:
Create a new column (ALTER TABLE dbo.MyTable ADD MyNewColumn DATE NULL;)
Update the new column using the old one (UPDATE dbo.MyTable SET MyNewColumn = CONVERT(DATE, MyColumn);)
Drop the old column (ALTER TABLE dbo.MyTable DROP MyColumn;) - Alternatively, you can rename this column instead and keep it as is)
Rename the new column (EXEC sp_rename 'dbo.MyTable.MyNewColumn', 'MyColumn', 'COLUMN';)
You might have to drop indexes beforehand, but this method (and it's alterations) help to prevent data loss.
If you encounter an error during casting, you should eliminate those values from the update (by for example adding a WHERE clause) and investigate them manually.
If you are using SQL Server 2012 or newer, you can use TRY_CONVERT() to ignore the values which cannot be converted to DATE. In this case you will have NULL in your new column.
Before you do anything, make sure, that all applications and code which is working with this column can handle the changes.
Notes
You might want to rebuild the table/indexes after a change like this.

Oracle SQL. How to change table field datatype CLOB-->VARCHAR2

I have database and some text fields are CLOB type, I need to change most of these into VARCHAR2.
Have tried to do that using SQL Developer tool, by clicking edit on table, but get error like this one:
The following SQL statement failed:
ALTER TABLE TBL_PEOPLE MODIFY (PERSON VARCHAR2(150) )
Want to ask, how can this change be done
You can't, directly. The code you tried will have got an `ORA-22859, presumably. (It's helpful to show the actual errors you get, of course).
You'll need to add a new varchar2 column; copy the data across - or a substring of it if it might be larger than the new column you're creating; drop the clob column. You can rename the columns so it looks fairly transparent.
As in this SQL Fiddle:
alter table tbl_people rename column person to clob_person;
alter table tbl_people add (person varchar2(150));
update tbl_people set person = clob_person;
alter table tbl_people drop column clob_person;
Obviously don't drop the old column until you're sure the data has copied without errors. Also take into account any constraints, indexes, etc. that might exist in the old column; they will need to be recreated. And anything that references the old column will have been invalidated - generally procedures will recompile themselves on next use.
So be careful, test it first, and plan some down time.
ALTER TABLE tablename ADD (FIELD_LIST_TEMP VARCHAR2);
UPDATE tablename SET FIELD_LIST_TEMP = FIELD_LIST;
ALTER TABLE tablename DROP COLUMN FIELD_LIST;
ALTER TABLE tablename RENAME COLUMN FIELD_LIST_TEMP TO FIELD_LIST;
Here FIELD_LIST existing column which is defined it as CLOB. With above query it will change from CLOB to VARCHAR2.

Microsoft SQL Compact Edition rename column

I am having problems renaming a column in SQL Server Compact Edition. I know that you can rename a table using sp_rename, but this doesn't work with columns.
I've searched for an alternative, but haven't found one.
Can I delete a column and then add a new one after a specific column? If I delete the column and add it after the a specified one the data would be lost right?
It seems that once you have created the table it can't be properly modified - is this another of the limitations of SQLCE?
It does indeed seem that SQL CE wont allow changing column names.
You're on the right track with creating a new column and deleting the old.
If you just add a column and delete the old you will lose the data so you need to issue an update statement to shift the data from the old to the new.
Something along the lines of
alter Table [dbo].[yourTable] add [newColumn] [DataType]
update yourTable set newColumn = oldColumn
alter Table [dbo].[yourTable] drop column [oldColumn]
Should create your new column, duplicate the data from old to new and then remove the old column.
Hope it helps!
sp_rename works with columns too:
EXEC sp_rename
objname = '< Table Name.Old Column Name >',
#newname = '<New Column Name>',
#objtype = 'COLUMN'
Example:
SP_RENAME 'MyTable.[MyOldColumnName]' , '[MyNewColumnName]', 'COLUMN'
UPDATE: Actually, The sp_rename procedure is not avialable in SQL CE! You can find the solution at http://www.bigresource.com/Tracker/Track-ms_sql-4Tvoiom3/
SDF Viewer has this function built in, you can also rename indexes, keys and relationships. Just right click on the name you want to change in the database treeview.

Altering a Table Column to Accept More Characters

What would the command be for Microsoft SQL Server 2008 to alter an existing column to allow for more characters? Would this have an effect on any previous entries in the column if I'm only expanding it?
I have a URL column that I need to add about 100 characters to.
ALTER TABLE [table] ALTER COLUMN [column] NVARCHAR(newsize)
And increasing the size won't affect your data.
ALTER TABLE myTable ALTER COLUMN myColumn varchar(100)
GO
This would not involve the risk of losing data, because you are expanding the size of the column.
ALTER TABLE tab ALTER COLUMN c VARCHAR(200)
You can use SQL Server Management Studio to generate the code to do this yourself. Just modify the table in the designer so that the column is wider and click "Generate change script" (under the "Table designer" menu).
Depending on the change you make the code to modify a table can be fairly complex.
It is quite simple:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(100)

Is there an easy way to add a custom migration script to SQL Compare scripts?

At my work we are currently having some serious pains pushing our database changes across environments. The issue starts to show up when we create a new non-nullable column on an existing table. The script that SQL Compare generates creates the column as non-nullable, so it will always fail. I was hoping that there was some alternative to having to manually edit the script. Is there any way to get around this? If not, how do you guys handle it?
Create a table:
create table #bingo ( id int )
Add a value:
insert into #bingo values (1)
Add a new column:
alter table #bingo add userid int
Populate the new column:
update #bingo set userid = 1 where id = 1
Change the new column to not nullable:
alter table #bingo alter column userid int not null
You would have to manually edit the RedGate Sql Compare to make it work like this.
How do you plan on filling the NOT NULL column? I don't see how SQL Compare could really come up with a solution since it has no way of knowing how you would fill it.
You could create the column with a DEFAULT, then simply add an update statement at the end of the generated scripts to properly update the column if you have some source for the values.
add a default onto the new not null column
when creating a new not null column, what value do all the existing rows get? If you don't know, make the column nullable.