如何向 SQL Server 中不允许空值的表添加列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1947447/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:50:36  来源:igfitidea点击:

How do I add a column to a table in SQL Server that doesn't allow nulls?

sqlsql-server

提问by KingNestor

I have a table that I want to add a bit column, which I wish to default to false for all existing data.

我有一个表,我想添加一个位列,我希望对于所有现有数据默认为 false。

How do I alter my table in such a way that it allows me to specify NOT NULL before I have inserted false for my existing rows?

如何更改我的表,以便在我为现有行插入 false 之前指定 NOT NULL?

Should I create it as nullable, do an insert than switch it non-nullable?

我是否应该将其创建为可空的,进行插入而不是将其切换为不可空的?

回答by Robert Christie

You could add the column and provide the default value to be used for all existing rows.

您可以添加该列并提供用于所有现有行的默认值。

ALTER TABLE foo 
ADD bar bit 
DEFAULT 0 NOT NULL;

回答by Cylon Cat

ALTER TABLE foo ADD bar bit DEFAULT 0 NOT NULL WITH VALUES;

The "with values" clause propigates the default value into existing rows.

“with values”子句将默认值传播到现有行中。

回答by gingerbreadboy

As an alternative to the answers listed there is another syntax available which may suit some people better, for example if you use tools like 'ReadyRoll'.

作为列出的答案的替代方案,还有另一种可能更适合某些人的语法,例如,如果您使用“ReadyRoll”等工具。

ALTER TABLE [dbo].[FOO] ADD BAR bit NOT NULL CONSTRAINT [df_Bar] DEFAULT 0

Check out this SO answerto see why naming your constraints (the df_Barabove) is nice.

查看这个 SO 答案,看看为什么命名你的约束(df_Bar上面的)很好。

回答by Bryan Batchelder

ALTER TABLE dbo.MyTable ADD MyColumn bit NOT NULL DEFAULT 0

For what it is worth, you can fire up Enterprise Manager, make the changes in the UI, and then have it generate a Change Script - and you can see how it would accomplish these kinds of tasks.

对于它的价值,您可以启动企业管理器,在 UI 中进行更改,然后让它生成一个更改脚本 - 您可以看到它如何完成这些类型的任务。

回答by MrEdmundo

I have also done it as you say "create it as nullable, do an insert than switch it non-nullable". I've not had a problem doing it this way.

我也按照您所说的“将其创建为可空,进行插入而不是将其切换为不可为空”来完成它。我这样做没有问题。

I've not yet needed to find a better way, however I'm intrigued if there is another way....

我还不需要找到更好的方法,但是我很好奇是否有另一种方法......

回答by Josh Mein

I usually create the field as nullable with a default as false in your case update all the fields that were in the database prior then switch it to null

我通常将字段创建为可空,在您的情况下默认为 false 更新数据库中的所有字段,然后将其切换为空