我在SQL Server数据库的表中有一个字段(比方说,foo),该表最初定义为可为空,但新要求表明此字段必须为非null.
在不删除表内容的情况下,通过更新脚本将此字段更新为非null的最佳方法是什么?我尝试从"设计"视图生成脚本,但在执行期间失败,因为表的当前内容具有foo的NULL值.更糟糕的是,如果我忽略了这个错误,它会继续删除表中的所有内容!
Cad*_*oux 10
NULL在将其NULL更改为之前,您必须在able列中为任何行设置一个值NOT NULL.
-- Clean up the data which won't comply with the schema changes
UPDATE t SET foo = 0 WHERE foo IS NULL
-- Apply the NOT NULL
ALTER TABLE t ALTER COLUMN foo int NOT NULL
-- Add a default for the future if that's what you want
ALTER TABLE t ADD CONSTRAINT t_foo_def DEFAULT 0 FOR foo
Run Code Online (Sandbox Code Playgroud)