将 NOT NULL 列插入现有表
我已经尝试过:
ALTER TABLE MY_TABLE
ADD STAGE INT NOT NULL;
但它给出了这个错误消息:
ALTER TABLE 只允许添加可以包含空值或 指定了默认定义
I have tried:
ALTER TABLE MY_TABLE
ADD STAGE INT NOT NULL;
But it gives this error message:
ALTER TABLE only allows columns to be added that can contain nulls or
have a DEFAULT definition specified
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
作为一个选项,您可以首先创建可为空的列,然后使用有效的非空值更新表列,最后使用 ALTER 列来设置 NOT NULL 约束:
另一个选项是为您的列指定正确的默认值:
UPD:请注意答案上面包含
GO
,当您在 Microsoft SQL Server 上运行此代码时,这是必须的。如果你想在 Oracle 或 MySQL 上执行相同的操作,你需要使用分号;
,如下所示:As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
Another option is to specify correct default value for your column:
UPD: Please note that answer above contains
GO
which is a must when you run this code on Microsoft SQL server. If you want to perform the same operation on Oracle or MySQL you need to use semicolon;
like that:如果您不允许该列为空,则需要提供默认值来填充现有行。例如,
在企业版上,这是一个 自 2012 年以来元数据仅发生变化
If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.
On Enterprise Edition this is a metadata only change since 2012
更快的解决方案
如果您像我一样需要在包含大量数据的表上执行此操作,则 ADD-UPDATE-ALTER 选项非常慢(数百万行可能需要数小时) 。
如果您也不希望表上有默认值,这里是创建列并删除默认约束的完整代码(即使对于大型表也几乎是即时的):
这是针对 SQL Server 的
A faster solution
If you, like me, need to do this on a table with a large amount of data, the ADD-UPDATE-ALTER option is very slow (it can take hours for millions of rows).
If you also don't want a default value on your table, here's the full code for creating a column and dropping the default constraint (pretty much instant even for large tables):
This is for SQL Server
错误消息非常具有描述性,请尝试:
The error message is quite descriptive, try:
其他 SQL 实现也有类似的限制。原因是添加列需要为该列添加值(逻辑上,即使不是物理上),默认为 NULL。如果您不允许
NULL
,并且没有default
,那么该值是什么?由于 SQL Server 支持
ADD CONSTRAINT
,因此我建议采用 Pavel 的方法,即创建可为 null 的列,然后在用非填充该列后添加
值。NOT NULL
约束。代码>NULLOther SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to
NULL
. If you don't allowNULL
, and don't have adefault
, what is the value going to be?Since SQL Server supports
ADD CONSTRAINT
, I'd recommend Pavel's approach of creating a nullable column, and then adding aNOT NULL
constraint after you've filled it with non-NULL
values.这对我有用,也可以从设计视图“借用”,进行更改 ->右键单击->生成更改脚本。
This worked for me, can also be "borrowed" from the design view, make changes -> right click -> generate change script.