如何将具有默认值的列添加到SQL Server 2000/SQL Server 2005中的现有表中?

推荐答案

语法:

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

例子:

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.

笔记:

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.

Sql相关问答推荐

如何编写SQL查询,在2024年每月的第一个日期输出货币?

平均SQL

提取Snowflake SQL中的嵌套键

无法找到正确的SQL查询需求

如何在SQL Server中列出从当前月份开始的过go 10年中的月份

删除MariaDB数据库中的JSON数据

如何根据特定的内部json元素值过滤postgres查询结果?

UPDATE查询中的乐观锁

SQL:如何查找聚合满足条件的连续日期

如果多行科目有一行在指定的日期范围内,如何 Select 该科目在该日期之前的所有行?

如何在AWS Athena中 Select JSON数组的最后一个元素?

基于开始/结束日期重叠的BigQuery突发行

JSON_VALUE 不适用于提取的 json 中的嵌套路径

如何计算两个非周期性时间序列+分组的重叠持续时间

SQL 语句将一列中的值与另一列中的不同值相加,同时按第三列进行分组?

如何在 JSONB 数组的每个对象中添加新的键值对- PostgreSQL

如何使用SELECT语句进行左连接,并根据右表中的特定值过滤结果?

使用 GROUP BY 时如何创建其他组?

条件意外地显着降低性能的地方

在给定列中具有特定值的行与 SQL 中的总行数的比率