Reputation: 3943
In SQL Server 2008, how can I forbid the delete (or throw an exception) if the involved record is used from others tables in some foreign keys?
I have set, in the relationship, "on delete -> nothing", but it isn't what I need... I need to stop the delete...
Let's say, if I have the table books and the table authors, and in books I have idAuthor, how can I forbid the delete of an author, if I have at least one book written by him?
Upvotes: 2
Views: 665
Reputation: 425208
For SQL Server use no action
:
alter table ...
add foreign key
...
on delete no action
Other databases use restrict
:
alter table ...
add foreign key
...
on delete restrict
In all cases, this option is the default and causes an exception to be thrown if the constraint would be violated by deletion of the parent row.
Upvotes: 1
Reputation: 1095
this happens by default in SQL Server - delete is not allowed for an entity that has foreign key rows (children) referencing it. So you should have "Enforce Foreign Key Constraints" set to YES in the Foreign Key Relation properties, by default.
This setting forces the server to throw an error when constraints are broken.
PS: I don't know where you are setting the "on delete -> nothing" in SQL Server.
Upvotes: 0