Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the datatype of a column from integer to text in SQL Server?

I need to change a database column from integer to string/text but I am not sure how to go about it.

This column is meant to store identification numbers, but recently the ID format changed and now the IDs contain ASCII characters as well (so with this change the new IDs cannot be stored as integers).

The application I am updating is written in Delphi 7 and uses the odbcexpress components for the SQL Server library.

Is it possible to use ALTER TABLE for this? Or does the data need to be copied to a new column as string, delete the old column, and rename the column to the old name?

Can you provide an example on how I might do this? I am not very familiar with the workings of SQL Server.

Thanks!

like image 603
Evan Zimmerman Avatar asked Jan 09 '15 00:01

Evan Zimmerman


People also ask

Can we convert int to string in SQL?

CONCAT function to join different data typesThe CONCAT implicitly converts values into strings. If you need to concatenate different data types, CONCAT is the best option instead of using the + character. Note: If you need to convert int into a string to compare, the cast and convert should be used.

How do you change data from one type to another in SQL?

SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds. GETDATE() implicitly converts to date style 0. SYSDATETIME() implicitly converts to date style 21.

Can we change the datatype of a column which has data?

We can use ALTER TABLE MODIFY COLUMN statement to change the datatype of the column. The syntax to change the datatype of the column is following. In the syntax, Tbl_name: Specify the table name that contains the column that you want to change.


1 Answers

ALTER TABLE is precisely what you want to do.

Your SQL might look something like this:

ALTER TABLE dbo.MyTable ALTER COLUMN MyColumn VARCHAR(20) NOT NULL;

Note that if you have columns that reference this one, you will have to update those as well, generally by dropping the foreign key constraints temporarily, making your changes, then recreating your foreign key constraints.

Don't forget to change anything that is dependent or downstream as well, such as any variables in stored procedures or your Delphi code.

Additional info related to comments (thanks, all):
This alter column operation will preserve data as it will be implicitly casted to the new type. An int casts to varchar without a problem so long as your varchar is wide enough to accommodate the largest converted value at least. For total safety with ints, I often use a varchar(11) or larger in order to handle the widest int value: negative two billion.

like image 113
Tim Lehner Avatar answered Sep 19 '22 17:09

Tim Lehner