SQL Server 对外键的约束

发布于 2024-12-11 07:25:19 字数 344 浏览 0 评论 0原文

我有一个 ItemComments 表,其中有一列带有外键约束,链接回第二个表中的项目条目。我将其视为一对多关系,因为第二个表中的每个项目可以有许多评论,但没有两个项目可以与 ItemComments 表中的相同评论条目关联,因此多对多关系不会申请。

问题:

我想在此列上定义一个约束,以防止更新外键值,即我想防止有人意外更改与特定 ItemComment 条目关联的项目 ID。我不太熟悉约束检查的表达式格式,并且很好奇此类操作的语法是什么。或者还有另一种更直接的方法来实现这一目标?感谢您的帮助。

更新

是否更好地实现交叉引用表,就像在多对多关系中那样以这种方式强制引用完整性?或者这会增加不必要的开销吗?

I have an ItemComments table that has one column with a foreign key constraint linking back to an item entry in a second table. I see this as a one-to-many relationship as each item in the second table can have many comments, but no two items can be associated with the same comment entry in the ItemComments table, so a many-to-many relationship does not apply.

PROBLEM:

I want to define a constraint on this column that will prevent the foreign key value from being updated, i.e. I want to prevent someone from accidentally changing the item ID that a specific ItemComment entry is associated with. I'm not very familiar with the expression formatting of constraint check and was curious what the syntax would be for such an action. Or is there another more straightforward way of accomplishing this? Thanks for the help.

UPDATE

Is it better to implement a cross-reference table as you would in a many-to-many relationship to enforce referential integrity in this way? Or is that adding more overhead than is necessary?

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

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

发布评论

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

评论(1

与风相奔跑 2024-12-18 07:25:19

您始终可以使用触发器。类似于:

create trigger dml_PreventUpdate
on YourTable
after update
as
    if UPDATE(ItemId)
    rollback

有两种类型的数据操作语言 (DML) 触发器。有一个 INSTEAD OF 和一个 AFTER/FOR 触发器(AFTERFOR 的功能相同)。顾名思义,INSTEAD OF 触发器在事务发生之前执行。顾名思义,AFTER 触发器在触发的操作之后执行。

基本上,此触发器所做的所有事情都是测试以查看 ItemId 列是否从针对表 YourTable 运行的 UPDATE 语句中更新。每次针对 YourTable 进行 UPDATE 时都会触发此触发器,但如果 ItemId 则只会ROLLBACK 事务是一个更新的字段。

You can always use a trigger. Something like:

create trigger dml_PreventUpdate
on YourTable
after update
as
    if UPDATE(ItemId)
    rollback

There's two types of Data Manipulation Language (DML) triggers. There's an INSTEAD OF and then an AFTER/FOR trigger (AFTER and FOR function the same way). An INSTEAD OF trigger, as the name implies, executes prior to the transaction taking place. An AFTER trigger, again as the name implies, executes after the triggered action.

Basically all this trigger is doing is testing to see if the ItemId column is updated from the UPDATE statement run against the table, YourTable. This trigger will fire every time there is an UPDATE against YourTable, but it will only ROLLBACK the transaction if ItemId is an updated field.

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