如何向表中添加多个列并在其中一个上添加默认约束?

新手上路,请多包涵

我想在现有表中添加 2 个新列。

其中之一应该是 NOT NULL 默认值为 0 (也填写在现有行中)。

我尝试了以下语法:

 Alter TABLE dbo.MamConfiguration
    add [IsLimitedByNumOfUsers] [bit]  NOT NULL,
    CONSTRAINT IsLimitedByNumOfUsers_Defualt [IsLimitedByNumOfUsers] DEFAULT 0
    [NumOfUsersLimit] [int] NULL
go

但它抛出异常。我应该怎么写?

原文由 Elad Benda 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 451
2 个回答

你可以使用这个:

 ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL DEFAULT 0,
    [NumOfUsersLimit] [INT] NULL
GO

或这个:

 ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL
        CONSTRAINT IsLimitedByNumOfUsers_Default DEFAULT 0,
    [NumOfUsersLimit] [INT] NULL
go

更多: 更改表

原文由 Iswanto San 发布,翻译遵循 CC BY-SA 3.0 许可协议

每一列都不一样;

 ALTER TABLE
    MamConfiguration
ADD
    Configuration1 BIT NULL, --this column is nullable
    Configuration2 BIT NOT NULL, --this column is not nullable
    Configuration3 BIT NOT NULL DEFAULT(0), --this column is not nullable and set default value is 0(zero)
    Configuration4 BIT NOT NULL CONSTRAINT DF_Configuration4 DEFAULT(0) --this column is not nullable and set default value is 0(zero) with spesific constraint name
GO

原文由 VolkanCetinkaya 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进