How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?
Sql – Add a column with a default value to an existing table in SQL Server
sqlsql serversql-server-2000sql-server-2005
sqlsql serversql-server-2000sql-server-2005
How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?
Best Answer
Syntax:
Example:
Notes:
Optional Constraint Name:
If you leave out
CONSTRAINT D_SomeTable_SomeCol
then SQL Server will autogeneratea 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 Nullableand you want the Default Value used for Existing Records.
If your Column is
NOT NULL
, then it will automatically use the Default Valuefor 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 SpecifySomeCol
's value, then it will Default to0
.If you insert a Record and Specify
SomeCol
's value asNULL
(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.