views:

2476

answers:

3

We have two columns in a database which is currently of type varchar(16). Thing is, it contains numbers and always will contain numbers. We therefore want to change its type to integer. But the problem is that it of course already contains data.

Is there any way we can change the type of that column from varchar to int, and not lose all those numbers that are already in there? Hopefully some sort of sql we can just run, without having to create temporary columns and create a C# program or something to do the conversion and so forth... I imagine it could be pretty easy if SQL Server have some function for converting strings to numbers, but I am very unstable on SQL. Pretty much only work with C# and access the database through LINQ to SQL.

Note: Yes, making the column a varchar in the first place was not a very good idea, but that is unfortunately the way they did it.

+6  A: 

The only reliable way to do this will be using a temp table, but it will not be much sql:

select * into #tmp from bad_table
truncate table bad_table
alter bad_table alter column silly_column int
insert bad_table
select cast(silly_column as int), other_columns
from #tmp
drop table #tmp
ck
#tmp is a random name of a tmp table?
Svish
Good answer - I would run this first - select cast(silly_column as int), other_columnsfrom bad_tableTo make sure you don't have any conversion issues and they are all in fact ints.
brendan
Of all the names I made up, you made a remark on the #tmp?
ck
haha, no no, I was wondering if the # character was what made it a temp table. or if it is just any name that doesn't already exist, or how it works...
Svish
A single # denotes a connection specific temp table (only available in that ocnnection) whereas a double hash ## denotes a global temp table (accessible by all connections)
ck
ah, nice, ok. then I think I got it *opening management studio to try it out*
Svish
*sigh* truncate doesn't work because of a foreign key constraint. can I somehow disable that while I mess with it and then turn it back on afterwards?
Svish
you can indeed, although it might be better if you do it in management studio than rely on my code from memory
ck
i was doing it in management studio. but by trying to write the query... is there another way of doing it? (also, is there any way to.. dry run a query? to see what it _would_ do, if you actually ran it?)
Svish
+1  A: 

Just change the datatype in management studio

(you may need to go to Tools > Options > Designers, and disable the option that prevents saving changes that re-create the table)

ctrlalt3nd
wont I lose all the values then??
Svish
No. Try it on a test table if you want?
ctrlalt3nd