In this post will discuss changing database table columns without dropping the table. Let’s understand this with an example we will be using table TblDoctors for this example.
Notice that this table has got Id DoctorName, gender, salary, and SpecializationId columns.And I have used the below create table script to create that table.
And if you notice the salary column data type is nvarchar(50).
This is the SQL script to populate it with some sample data.
Let’s say based on the table, we want to write a query which is going to list the total salaries of doctors grouped by gender. So we want the output to be like the below image.
So let’s write a query for that.
if we try to execute the query, it will give an error.
So basically this error message is stating we cannot use the salary column, with Sum() aggregate function. because it’s data type is nvarchar. So we need to change the data type of salary column from nvarchar to float,int or decimal.
And one way to do that within the object explorer. Right-click on the table TblDoctors click design and notice the data type of the salary column is nvarchar, let’s change it to Integer and let’s try to save it and see what’s going to happen.
we get a warning. Saving changes is not permitted. Basically, this is telling us we need to drop and recreate the table.
And if you remember, this table has already got some data as well. So if we drop and recreate it, we are going to lose that data. So how do we get rid of this warning message?
Basically there are two ways.
we can use a SQL query to alter the column. so instead of using the SQL server designer, we can simply use a SQL query.
So let’s execute that and see if it works as expected. Look at that. It works as expected. So this is one option.
2 .Option 2 is basically to disable option prevent saving changes that require a table recreation in SQL server.
All we need to do is disable that option. And to do that, within the tool select options and then expand designers and under that table and database designers and uncheck the checkbox, prevent saving changes that require table creation.
- Now you can change the column datatype from designer also. let’s try
Right-click on table ->select designer
- and then let’s try to change the salary datatype to decimal.
- Let’s save the changes and see where it works.