代码之家  ›  专栏  ›  技术社区  ›  PassionateDeveloper

SQL Server 2008:无法保存,因为必须删除表并新建才能保存?

  •  3
  • PassionateDeveloper  · 技术社区  · 14 年前

    我有点不理解这个问题。

    我正在使用MS SQL Management Studio 2008。 我有一个全新的带有表X的数据库。

    X有3列:

    • ID,唯一标识符,不为空

    3 回复  |  直到 14 年前
        2
  •  2
  •   Tim    14 年前

    为了澄清不信者Damien_u所说的话(编辑:我现在看到他已经扩展了他的回复),您在添加非空约束之前输入的前几行在电子邮件列中没有任何值,因此将违反非空约束。首先,添加email列,允许空值。然后编辑现有行,使它们在该列中具有值。然后返回并向email列添加非空约束。 或者,您可以在定义列时(临时)为电子邮件提供一个默认值,例如“temp@somedomain.com”,现有行将获得该默认值(如果没有提供电子邮件,新行也将获得该默认值)。然后你可以回去编辑它们。

    简单地说,规则是:如果一行或多行违反了约束,则不能向已经填充了数据的表添加约束。

    “约束”是您希望数据库强制执行的规则。

        3
  •  1
  •   Damien_The_Unbeliever    14 年前

    如果不指定列的默认值,就不能执行此操作-否则,SQL Server如何确保表中现有行的“非空”约束?

    如果你试图通过一个查询来完成,你会得到更多的解释:

    ALTER TABLE Table_2 ADD Email varchar(100) not null
    
    Msg 4901, Level 16, State 1, Line 1
    ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'Email' cannot be added to non-empty table 'Table_2' because it does not satisfy these conditions.