SQL Server 对外键的约束
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您始终可以使用触发器。类似于:
有两种类型的数据操作语言 (DML) 触发器。有一个
INSTEAD OF
和一个AFTER/FOR
触发器(AFTER
和FOR
的功能相同)。顾名思义,INSTEAD OF
触发器在事务发生之前执行。顾名思义,AFTER
触发器在触发的操作之后执行。基本上,此触发器所做的所有事情都是测试以查看
ItemId
列是否从针对表YourTable
运行的UPDATE
语句中更新。每次针对YourTable
进行UPDATE
时都会触发此触发器,但如果ItemId
则只会ROLLBACK
事务是一个更新的字段。You can always use a trigger. Something like:
There's two types of Data Manipulation Language (DML) triggers. There's an
INSTEAD OF
and then anAFTER/FOR
trigger (AFTER
andFOR
function the same way). AnINSTEAD OF
trigger, as the name implies, executes prior to the transaction taking place. AnAFTER
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 theUPDATE
statement run against the table,YourTable
. This trigger will fire every time there is anUPDATE
againstYourTable
, but it will onlyROLLBACK
the transaction ifItemId
is an updated field.