Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add a new column with an initial (but not default) value?

I need to add a new column to a MS SQL 2005 database with an initial value. However, I do NOT want to automatically create a default constraint on this column. At the point in time that I add the column the default/initial value is correct, but this can change over time. So, future access to the table MUST specify a value instead of accepting a default.

The best I could come up with is:

ALTER TABLE tbl ADD col INTEGER NULL UPDATE tbl SET col = 1 ALTER TABLE tbl ALTER COLUMN col INTEGER NOT NULL 

This seems a bit inefficient for largish tables (100,000 to 1,000,000 records).

I have experimented with adding the column with a default and then deleting the default constraint. However, I don't know what the name of the default constraint is and would rather not access sysobjects and put in database specific knowledge.

Please, there must be a better way.

like image 383
Adrian Avatar asked Jun 25 '09 05:06

Adrian


People also ask

Can column be altered to add default values?

You cannot alter a column to specify a default value if one of the following conditions exists: The table is referenced by a view.

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 .


1 Answers

To add the column with a default and then delete the default, you can name the default:

ALTER TABLE tbl ADD col INTEGER NOT NULL CONSTRAINT tbl_temp_default DEFAULT 1 ALTER TABLE tbl drop constraint tbl_temp_default 

This filled in the value 1, but leaves the table without a default. Using SQL Server 2008, I ran this and your code, of alter update alter and did not see any noticeable difference on a table of 100,000 small rows. SSMS would not show me the query plans for the alter table statements, so I was not able to compare the resources used between the two methods.

like image 102
Shannon Severance Avatar answered Oct 07 '22 09:10

Shannon Severance