可以替换或更新 SQL 约束吗?

发布于 2024-07-19 08:39:00 字数 218 浏览 5 评论 0原文

我为名为“grade”的列编写了以下约束:

CONSTRAINT gradeRule CHECK grade IN (‘easy’, ‘moderate’, ‘difficult’),

以后是否可以将 gradeRule 更新为具有不同的值? 例如,“中等”和“困难”可以更改为“中等”和“困难”。

谢谢

I have written the following constraint for a column I've called 'grade':

CONSTRAINT gradeRule CHECK grade IN (‘easy’, ‘moderate’, ‘difficult’),

Is it possible to later update the gradeRule to have different values? For example, 'moderate' and 'difficult' could be changed to 'medium' and 'hard'.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

还不是爱你 2024-07-26 08:39:00

您可以删除现有约束,并使用 NOCHECK 选项添加新约束。 这将允许您添加约束,即使表中的数据违反了约束。 但这样做的问题是,如果不先让现有记录通过约束,您将无法更新它们。

ALTER TABLE SomeTable DROP CONSTRAINT gradeRule
GO
ALTER TABLE SomeTable ADD CONSTRAINT gradeRule ... WITH NOCHECK
GO

尽管这是可能的,但通常不建议这样做,因为未来数据更新可能会出现问题。

You could drop the existing constraint, and add the new constraint with the NOCHECK option. This would allow you to add the constraint even though data in the table violates the constraint. The problem with doing this though would be that you wouldn't be able to update existing records without making them pass the constraint first.

ALTER TABLE SomeTable DROP CONSTRAINT gradeRule
GO
ALTER TABLE SomeTable ADD CONSTRAINT gradeRule ... WITH NOCHECK
GO

Although this is possible, its not usually recommended because of the potential problems with future updates of the data.

日裸衫吸 2024-07-26 08:39:00

删除约束,然后添加替换约束。
至少不能更新 SQL Server 中的约束。

ALTER TABLE SomeTable DROP CONSTRAINT gradeRule

此外,您需要在添加新约束之前更新表数据,使其满足新约束。

Drop the constraint, and then add the replacement constraint.
You can't update a constraint in SQL Server at least.

ALTER TABLE SomeTable DROP CONSTRAINT gradeRule

In addition, you'll need to update the table data before adding the new constraint, so that it meets the new constraint.

情深缘浅 2024-07-26 08:39:00

如果更改约束,表中当前的所有数据都必须满足约束。 因此,如果您有 2 行“中等”数据,并尝试将约束更改为简单、中等和困难,它不会让您这样做。

因此,您必须制定新的约束(简单、中等、中等、困难、困难),或者将数据更新为新值 - 中等 --> 中等等

If you change the constraint, all of the data currently in the table must meet the constraint. So if you had 2 rows of data with 'moderate' and tried to change the constraint to easy, medium, and hard, it would not let you.

So you would have to make the new constraint (easy, moderate, medium, difficult, hard) or, update the data to the new values - moderate --> medium etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文