views:

528

answers:

5

I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good.

Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row event.

Is this possible?

+1  A: 
If Exists ( Select * From OtherTable
            Where OtherTableFKColumn = MainTablePrimaryKey) 
   Begin
       Rollback Transaction
       RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
   End
Charles Bretana
OK this is a valid approach, but what If someone later on adds other tables which are linken to this table. This code must then be changed.
Drejc
oh, you need one of these for each table that has a FK to the main table... If that list changes, then yes this code would have to be modified to add an additional statement for that additional table.
Charles Bretana
+1  A: 

Other than checking the COUNT(*) of every related table? I don't think so.

Tomalak
A: 

One ugly attempt would be to try a DELETE in a transaction and then force a ROLLBACK if it is successful. But this is to dirty for my taste.

Drejc
Didn't he say he wants to do a check before the DELETE?
FelixM
A: 

This is a question that on the surface looks good, but has implications.

First of all, you'd need to ensure that after you've read the status of those relations, nobody could change those, so obviously you need to use a transaction and lock the rows in question.

Then you need a way to figure out what relations to check, as I see in a comment here your question about what happens if someone later adds a new relation. So you need to query the schema, or perhaps auto-generate this code from the schema, so that the detection mechanism only needs to run each time you change the schema.

Now, does the exception you get really seem that expensive after this ordeal?

Lasse V. Karlsen
The main problem is that the database design is not perfectly suited for the given task.But the fact is the database can not be changed so I need to find a workaround for a perticular problem.Plus I can not get to the schema data (master database).So I'm just curious what different ideas will pop up
Drejc
A: 

I don't think it's a good idea to attempt something like this because it means that every foreign key has to be checked twice: once by you beforehand, and then again by the server when you execute your SQL. The performance implications could be severe.

However, if you have your mind set on doing this, the most generic way involves using the database's data dictionary. I am not familiar with the SQL Server data dictionary, but other relational databases store all their metadata in database tables that you can query. You could find all the foreign keys that reference your table and dynamically build queries which look for dependent rows.

FelixM