SQL 添加默认约束的命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4307075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Command for adding a default constraint
提问by Randy Minder
There appears to be at least two ways to add a default constraint using straight T-SQL. Am I correct that the only difference between the two below is that the second method specifically creates a name for the constraint, and the first method has one generated by SQL Server?
似乎至少有两种方法可以使用直接 T-SQL 添加默认约束。我是否正确,以下两者之间的唯一区别是第二种方法专门为约束创建了一个名称,而第一种方法有一个由 SQL Server 生成的名称?
ALTER TABLE [Common].[PropertySetting] ADD DEFAULT ((1)) FOR [Active];
ALTER TABLE [Common].[PropertySetting] ADD CONSTRAINT [DF_PropertySetting_Active) DEFAULT ((1)) FOR [Active];
回答by gbn
Pretty much, yes for an ALTER TABLE
几乎,是的,对于 ALTER TABLE
You can add a columnn with default in one step for CREATE or ALTER too.
您也可以一步为 CREATE 或 ALTER 添加一个默认列。
ALTER TABLE foo ADD bar varchar(100) CONSTRAINT DF_Foo_Bar DEFAULT ('bicycle')
ALTER TABLE foo ADD bar varchar(100) DEFAULT ('bicycle')
As you noted, the system generates a name if one is not supplied. CONSTRAINT constraint_name
is optional says MSDN. The same applies to any columnor tableCONSTRAINT
正如您所指出的,如果未提供名称,系统会生成一个名称。CONSTRAINT constraint_name
MSDN 说是可选的。这同样适用于任何列或表CONSTRAINT
EditIf the column was already created, and you only want to add the constraint use:
编辑如果已经创建了列,并且您只想添加约束,请使用:
ALTER TABLE TableName ADD CONSTRAINT DF_Foo_Bar DEFAULT 'bicycle' FOR FieldName;