Can I check for constraints before a delete in SQL Server?

点点圈 提交于 2019-12-05 13:36:05
If Exists ( Select * From OtherTable
            Where OtherTableFKColumn = MainTablePrimaryKey) 
   Begin
       Rollback Transaction
       RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
   End

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

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.

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?

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!