Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to defer referential integrity checks until the end of a transaction in SQL Server?

I recently read in Fowler's PofEA that some database engines allow you to defer RI checks until the end of the transaction. Is this possible in SQL Server?

The problem comes with some scenarios where I am trying to save changes that include insertions and deletions, it can be tricky to determine the correct order in which to perform the operations to avoid RI failures. I know that at the end of the transaction the RI will be good so it would seem ideal to defer these checks.

like image 359
Darrel Miller Avatar asked Aug 25 '09 18:08

Darrel Miller


4 Answers

Looks like sql server doesn't allow this, but you aren't the only one who wants it. It's part of the SQL 92 standard, so they've had 17 years now to figure it out. Then again, MySQL doesn't support it either (although Oracle does).

Reordering the statements is probably your best option.

like image 87
Eric Petroelje Avatar answered Sep 23 '22 17:09

Eric Petroelje


You would be better off determining the correct order so that the transaction can fail at the appropriate time. This should be a one-time determination.

like image 43
Adam Robinson Avatar answered Sep 22 '22 17:09

Adam Robinson


SQL Server does not have this feature.

May I humbly suggest that if it's tricky to determine the correct insertion order (or there is not one), that your database design may need to be refactored or at least examined very carefully.

like image 28
Cade Roux Avatar answered Sep 24 '22 17:09

Cade Roux


If you are on SQL Server 2008, you can use MERGE to combine insert/delete into a single RI-safe transaction...

like image 23
gbn Avatar answered Sep 21 '22 17:09

gbn