kingrichard2005
kingrichard2005

Reputation: 7289

SQL Server constraints on foreign keys

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?

Upvotes: 0

Views: 212

Answers (1)

user596075
user596075

Reputation:

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.

Upvotes: 1

Related Questions