Can I check for constraints before a delete in SQL

2019-05-04 14:30发布

问题:

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:

If Exists ( Select * From OtherTable
            Where OtherTableFKColumn = MainTablePrimaryKey) 
   Begin
       Rollback Transaction
       RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
   End


回答2:

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



回答3:

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.



回答4:

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?



回答5:

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.