Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a column without dropping a table in SQL 2008

Why does SQL 2008 all of a sudden want to drop my tables when I go to change the column type from say int to real? This never happened in SQL 2005 to my knowledge. Any insight would be helpful please.

like image 892
Middletone Avatar asked Jan 20 '09 04:01

Middletone


People also ask

How do I change the datatype of a column in SQL without dropping the table?

So to do that go to SQL Server and within Tools select Options. Now in the option window expand Designers and under that "Table and Database Designers" and uncheck the check box "Prevent saving changes that require table re-creation" then click OK.

How do you add a new column in SQL without dropping a table?

You can add a column without dropping the table. If you want the column NOT NULL then you'll have to make it accept NULL first, then set the values through an update, and lastly alter the column to NOT NULL .


2 Answers

I can't believe the top answer has been sitting here for so long - it is very dangerous advice!

There are few operations that you can do inplace without dropping your table:

  • Expand a varchar column https://dba.stackexchange.com/questions/5211/changing-column-width
  • Make a column nullable (but not vice-versa)
  • Renaming columns using sp_rename

If you find yourself in the situation where altering a column is not possible without dropping the table, you can usually use a SELECT INTO query to project your data into a new table, then drop the old table (temporarily disabling constraints) and then renaming the projected table. You will need to take your database offline for maintenance in this case though.

like image 59
Johannes Rudolph Avatar answered Sep 27 '22 21:09

Johannes Rudolph


Here is what I use:

-- Add new column ALTER TABLE MyTable ADD Description2 VARCHAR(MAX) GO  -- Copy data to new column (probably with modifications) Update MyTable SET Description2 = Description GO  -- Drop old column ALTER TABLE MyTable DROP COLUMN Description GO  -- Rename new column to the original column's name. sp_RENAME 'MyTable.Description2' , 'Description', 'COLUMN' GO 
  1. Copy the data into a new column.
  2. Drop the old column.
  3. Rename the new column to the old column's name.
like image 28
user2173353 Avatar answered Sep 27 '22 22:09

user2173353