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).
CREATE TABLE [dbo].[TblDoctors]( [Id] [int] IDENTITY(1,1) NOT NULL, [DoctorName] [nvarchar](max) NOT NULL, [Gender] [nvarchar](50) NULL, [Salary] [nvarchar](50) NULL, [SpecializationId] [int] NULL, CONSTRAINT [PK_TblStudent] PRIMARY KEY CLUSTERED ( [Id] ASC ) ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
This is the SQL script to populate it with some sample data.
SET IDENTITY_INSERT [dbo].[TblDoctors] ON GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (1, N'Carter', N'Male', N'20000', 1) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (3, N'Gianna', N'Female', N'10000', 1) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (4, N'Brandon', N'Male', N'15000', 4) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (5, N'Julia', N'Female', N'23000', 7) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (6, N'Julian', N'Male', N'45000', 6) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (7, N'Kayla', N'Female', N'25000', 5) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (9, N'Autumn', N'Female', N'13000', 1) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (10, N'Sebastian', N'Male', N'35000', 2) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (11, N'Blake', N'Male', N'39000', 3) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (12, N'Dr. Jacob', N'Male', N'41000', 4) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (13, N'Dr. Henry', N'Male', N'28000', 5) GO INSERT [dbo].[TblDoctors] ([Id], [DoctorName], [Gender], [Salary], [SpecializationId]) VALUES (14, N'Dr. Tanmay', N'Male', N'36000', 1) GO SET IDENTITY_INSERT [dbo].[TblDoctors] OFF GO
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.
Select Gender, Sum(Salary) as Total from TblDoctors Group by Gender
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.
Alter table TblDoctors Alter column Salary float
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.
The post How to change database table columns without dropping the table appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- Is there any way to find a specific value in every field of every table in Microsoft SQL Server?
- Stored procedure to update table in SQL
- how to select two table and merge the data not to show the duplicate
- Using Variable in SQL Query Raises ADO Error
- How to inner join multiple columns?
- T-SQL IN Clause Combined With Case Statement
- MS SQL Server 2005 - How to Auto Increment a field (not primary key)
- Combine multiple rows into list for multiple columns
- Entity Framework There is already an open DataReader associated with this Command which must be closed first
- EXEC Select Statement With Dynamic Column stores value into a Variable
- SQL Update Part of XML string in a column
- how to search a date by month in sql server c#
- How to import selective tables using SSIS based on custom (e.g.XML) file
- Connect to a SQL Server database
- Oracle Linked Server in SQL Server 2017
- Explanation for the fn_dblog() function's output on SQL Server 2008 R2
- SQL Server 2008 - Updating only a specific number of rows within a table
- Modify select query with multi condition cases
- Multiple Results with One Query
- SQL comma separated column loop
- select records where words from a table appear in a field on a different table
- update with reg ex or
- How to change the retention period for CDC or put a condition on it (SQL Server 2012)
- SQL Pivot rows to columns without aggregate
- Webtrends can't read Microsoft reporting services 2008 web log
- load each table data to html table using label
- Query for sum of all and particular rows
- SQL Server 2008 R2 Calculated Field Issue
- Auto increment column from DB in ListView
- Always save a constant to a SQL Server field
- How to determine if two records are 1 year apart (using a timestamp)
- Cast Stored Procedure Result as a Table?
- use of Isnull() in optimization
- Count number of distinct values based on another set of distinct values
- how to write select max with row?
- How to join dynamic sql statement in variable with normal statement
- How can I make this query recursive Sql Server?
- Need to find out the date 1 year and 1 year ago from today in SQL
- SSIS- Split output into multiple files
- Associate employees to departments based on hierarchy tree
- What's the best way to store different images in the database?
- how to generate salary total sql server
- SQL Server Case statement for date condition
- SQL Server 2008 R2 restore error
- How do I Pivot on an XML column's attributes in T-SQL
- Combine 2 different median values in the same column
- SQL Server : check boolean can only occur once as true
- How can I deal with the return of a null value parameter from a stored procedure to C# code?
- trigger to Send mail when inserted record as PDF file
- Cannot convert char to datetime in windows counters table
- SQL Server substring without upper bound
- SQL - Insert Where Not Exists
- How to retrieve data from SQL Server as required below?
- Export multiple stored procedures to text files
- Truncated String Data error when inserting into an nvarchar(max) field
- Find two consecutive rows
- Handle missing data in SQL Server 2012 SELECT statement
- Create table under a specific FileGroup WHERE 1=2
- Extract inversed duplicated values sql
- Need help to troubleshoot a slow query
- Combine multiple boolean columns into a single column
- SQL insert into using Union should add only distinct values
- MSSQL 17 is using only half of the avaliable processors
- which is faster for running SQL on small tabular data (250 records), XML or SQL server?
- Truncate table then insert data into same table only inserts 1 record
- Joining two tables on multiple values of the joining column
- SQL Azure: list all logins and users
- Issue with a WHERE clause
- How to copy data in identity column?
- Cannot insert duplicate key row in object
- Need a query to insert 'level' into an adjacent list
- Append a New Line onto each concatenated row from SQL Server
- sql Could not find stored procedure ''. with bit as a return type
- Asp inserting error
- How to copy data from one table into another in Microsoft SQL Server
- Copy column values from one table to another
- How do I join the results of two queries in SQL Server?
- Inserting CSV with blank value into SQL table with BIGINT column
- Use a different WHERE in no results
- Total Row Count in sql query---sql server 2008
- Horrible sql server performance when capturing result in variable
- Insert OUTPUT Insert.id to another table in multiple values insert
- How to add Transactions with a DataSet created using the Add Connection Wizard?
- Concatenate multiple rows from multiple tables
- SQL Server 2014 In-Memory previous transaction aborted exception
- Microsoft SQL server to select Top N group
- Retrieve an element without sub-elements in SQL Server
- PowerBI embedded with Direct Query gets white screen and 403
- SQL 2014 - How to add incremental value for each row of non identity column
- How to connect a new query script with SSMS add-in?
- Can't get powershell to handle a SQL Server connection failure
- SQL Server dynamic JSON using within Analysis Services?
- subquery - how to refer to outer query value
- Query Using != On LEFT JOIN Table Returns No Result
- Application execute complex SQL query
- Insert rows from one table to columns of another table with specific pattern
- Easy plugin or procedure for sqlserver Management Studio to script row inserts
- Is there a better way to do this join?
- sql select records with matching subsets
- How do I import columns into Excel from SQL in the same order as they are in SQL Server?
- How do i delete a record from 2 table which have relationship?
- Inserting multiple rows into SQL Server 2008 table, copied from other rows with one column changed
- Long XML throwing exception when saving in NHibernate
- Replacing data in JSON using SQL query
- Exception Access Violation in SQL
- Find groups containing 6 consecutive 1s in one column
- Avoiding SQL injection using a non parameterised query
- SQL Server 2012 OUT OF MEMORY error messages
- Cannot connect to SQL Server via VB.net but I can login to the server from SSMS with the same cridentials
- SQL Server - Unexpected behavior with ISNULL/NULLIF
- Why cast/convert from int returns an asterisk
- Why does INNER JOIN multiplies all rows if I join on itself?
- Outer Join Or special Union
- How to clear data from tables with foreign key contraints in SQL Azure
- Entity Framework startup slow on everyone's computer but mine
- Python: Set param for columns and values pypyodbc - executemany
- Bing.com and SQL Server FTS?
- What are T-SQL Statement Blocks?
- Combine multiple html rows into one
- How do I do a boolean string comparison in SQL Server 2008
- Adding hidden value of a column in SQL Server using C# in combobox
- Export MySQL tables into Microsoft SQL server
- SQL Query Advice - Get Previous Customer Order
- How to know whether a name exists on a particular sql table in c#?
- How to parse JSON string recursively by using mssql?
- Select Max Limit 1 from Group
- Computed Column for Adding Date based on another Date and foreign key column
- How to select boolean column based on the other column value in SQL?
- SSRS: Table on new page if it passes a page break
- find out who added new column in table
- Pagination on fast changing database content
- Retrieve only one row using left join based on foreign key
- How to default the time for the date with SQL Server
- Passing a variable into an IN clause within a SQL function?
- SQL SERVER - Create Table by matching rows and columns and put Y or N
- PHP Person Search with explode
- DataAdapter: Update unable to find TableMapping['Table'] or DataTable 'Table'
- Why do I get significantly improved performances by performing the described modification in a SQL query?
- How to generate table name by datetime?
- Record rows updated through SSIS execute task
- Split Multipile delimiter from SQL String
- SQL does table partitioning automatically partition indexes?
- "metadata could not be determined" when importing with bcp from command line
- Why doesn't sql compare times?
- Not able to connect any remote database server after installing Visual studio 2012
- Sql server DELETE and WITH clause
- Retain NULL not working for all columns
- Delete information from transaction logs at SQL Server
- Split FOR XML PATH results into separate rows
- SQL Server: error converting data type nvarchar to float