Add a column with a default value to an existing table in SQL Server(将具有默认值的列添加到 SQL Server 中的现有表)
问题描述
如何在 SQL Server 2000中的现有表中添加具有默认值的列a>/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.
注意事项:
可选的约束名称:
如果您省略 CONSTRAINT D_SomeTable_SomeCol,则 SQL Server 将自动生成
具有有趣名称的默认约束,例如:DF__SomeTa__SomeC__4FB7FEF6
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
可选的 With-Values 语句:WITH VALUES 仅在您的 Column 为 Nullable 时才需要
并且您想要用于现有记录的默认值.
如果您的 Column 是 NOT NULL,那么它将自动使用默认值
对于所有现有记录,无论您是否指定 WITH VALUES.
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.
插入如何使用默认约束:
如果你在 SomeTable 中插入一个 Record 并且 not 指定 SomeCol 的值,那么它将默认为 <代码>0.
如果您插入记录并且将SomeCol的值指定为NULL(并且您的列允许空值),
那么默认约束将不被使用,NULL将作为值插入.
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.
注释是基于以下每个人的出色反馈.
特别鸣谢:
@Yatrix、@WalterStabosz、@YahooSerious 和 @StackMan 发表评论.
Notes were based on everyone's great feedback below.
Special Thanks to:
@Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
这篇关于将具有默认值的列添加到 SQL Server 中的现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将具有默认值的列添加到 SQL Server 中的现有表
基础教程推荐
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
