Efficiently managing SQL Server databases often requires adding columns to existing tables, especially when a predefined default value is needed for data integrity and streamlined data handling. This guide explains how to accomplish this in SQL Server 2000 and 2005.
The following SQL syntax adds a column with a default value:
<code class="language-sql">ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL | NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES;</code>
Here's a practical example:
<code class="language-sql">ALTER TABLE SomeTable ADD SomeCol BIT NULL -- Specify NULL or NOT NULL as needed. CONSTRAINT D_SomeTable_SomeCol -- Optional constraint name. DEFAULT (0) -- Optional default value. WITH VALUES; -- Essential if the column allows NULLs and you want to apply the default to existing rows.</code>
CONSTRAINT D_SomeTable_SomeCol
results in SQL Server automatically generating a more complex default constraint name.WITH VALUES
Clause: This clause is crucial only when the column permits NULL values and you intend to apply the default value to existing rows. For NOT NULL
columns, the default value is automatically applied to existing rows regardless of this clause.SomeCol
is omitted during data insertion, it defaults to 0. However, if SomeCol
is defined as NULL
and allows NULLs, the default constraint is bypassed, and NULL
is inserted.Adding a column with a default value to an existing SQL Server table is a simple yet powerful technique. Following the provided syntax and guidelines ensures data integrity and simplifies database management.
The above is the detailed content of How to Add a Column with a Default Value to an Existing SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!