简体   繁体   中英

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

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

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?

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

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;
ALTER TABLE foo ADD bar bit DEFAULT 0 NOT NULL WITH VALUES;

“with values”子句将默认值指定为现有行。

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'.

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

Check out this SO answer to see why naming your constraints (the df_Bar above) is nice.

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

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

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....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM