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?
You can always use a trigger. Something like:
There’s two types of Data Manipulation Language (DML) triggers. There’s an
INSTEAD OFand then anAFTER/FORtrigger (AFTERandFORfunction the same way). AnINSTEAD OFtrigger, as the name implies, executes prior to the transaction taking place. AnAFTERtrigger, again as the name implies, executes after the triggered action.Basically all this trigger is doing is testing to see if the
ItemIdcolumn is updated from theUPDATEstatement run against the table,YourTable. This trigger will fire every time there is anUPDATEagainstYourTable, but it will onlyROLLBACKthe transaction ifItemIdis an updated field.