SQL 如何向表中添加多个列并在其中之一上添加默认约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15184939/
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
How to add multiple columns to a table and add default constraint on one of them?
提问by Elad Benda
I want to add 2 new columns to existing table.
我想向现有表添加 2 个新列。
One of them should be NOT NULL
with default value 0(filled in the existing rows as well).
其中之一应该是NOT NULL
默认值0(也填充现有行)。
I have tried the following syntax:
我尝试了以下语法:
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?
但它抛出异常。我应该怎么写?
回答by Iswanto San
You can use this:
你可以使用这个:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
GO
or this:
或这个:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL
CONSTRAINT IsLimitedByNumOfUsers_Default DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
go
More: ALTER TABLE
更多:改变表
回答by Praveen Nambiar
Try this.
尝试这个。
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [bit] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [int] NULL
回答by Arulmouzhi
To add multiple columns to a table and add default constraint on one of them-
要将多个列添加到表中并在其中之一上添加默认约束 -
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] CONSTRAINT Def_IsLimitedByNumOfUsers DEFAULT(0) NOT NULL,
[NumOfUsersLimit] [INT] NULL;
GO