Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column with a default value to an existing table in SQL Server

How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?

like image 396
Mathias Avatar asked Sep 18 '08 12:09

Mathias


People also ask

How can a column with a default value be added to an existing table?

How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005? ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint.

How do I add a column to an existing table in SQL query?

Syntax. The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.


2 Answers

Syntax:

ALTER TABLE {TABLENAME}  ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}  CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES 

Example:

ALTER TABLE SomeTable         ADD SomeCol Bit NULL --Or NOT NULL.  CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.     DEFAULT (0)--Optional Default-Constraint. WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. 

Notes:

Optional Constraint Name:
If you leave out CONSTRAINT D_SomeTable_SomeCol then SQL Server will autogenerate
    a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6

Optional With-Values Statement:
The WITH VALUES is only needed when your Column is Nullable
    and you want the Default Value used for Existing Records.
If your Column is NOT NULL, then it will automatically use the Default Value
    for all Existing Records, whether you specify WITH VALUES or not.

How Inserts work with a Default-Constraint:
If you insert a Record into SomeTable and do not Specify SomeCol's value, then it will Default to 0.
If you insert a Record and Specify SomeCol's value as NULL (and your column allows nulls),
    then the Default-Constraint will not be used and NULL will be inserted as the Value.

Notes were based on everyone's great feedback below.
Special Thanks to:
    @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.

like image 171
James Boother Avatar answered Sep 30 '22 12:09

James Boother


ALTER TABLE Protocols ADD ProtocolTypeID int NOT NULL DEFAULT(1) GO 

The inclusion of the DEFAULT fills the column in existing rows with the default value, so the NOT NULL constraint is not violated.

like image 21
dbugger Avatar answered Sep 30 '22 10:09

dbugger