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

2021-09-10 00:00:00 sql tsql sql-server

我想向现有表中添加 2 个新列.

I want to add 2 new columns to existing table.

其中一个应该是 NOT NULL,默认值为 0(也填写现有行).

One of them should be NOT NULL with default value 0 (filled in the existing rows as well).

我尝试了以下语法:

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

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

But it throws exception. How should I write it?

推荐答案

你可以使用这个:

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

更多:ALTER TABLE

相关文章