debugsqlMajor
Is there a way to test whether DELETE will fail due to constraints?
Viewed 0 times
dueconstraintsdeletewayfailwilltesttherewhether
Problem
I'd like to be able to predict whether a
What are my options for doing this? Is there a simple way to do a "dry run" of a
We need to run a batch of several
I'm trying to make sure they all succeed, or none of them succeed.
DELETE will run into a constraint violation, without actually performing the delete.What are my options for doing this? Is there a simple way to do a "dry run" of a
DELETE?We need to run a batch of several
DELETEs in separate transactions. If one fails, the others are already committed. (Bad design from the start, I know, but it's not my application, and it's not changing.) The best workaround at the moment sounds like doing a dry check to see if the DELETEs will fail.I'm trying to make sure they all succeed, or none of them succeed.
Solution
If your goal is to process all deletes only if they all succeed, why not just use TRY/CATCH:
If the goal is to allow all successful deletes to succeed even if one or more will fail, then you can use individual TRY/CATCH, e.g.
BEGIN TRANSACTION;
BEGIN TRY
DELETE #1;
DELETE #2;
DELETE #3;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCHIf the goal is to allow all successful deletes to succeed even if one or more will fail, then you can use individual TRY/CATCH, e.g.
BEGIN TRY
DELETE #1;
END TRY
BEGIN CATCH
PRINT 1;
END CATCH
BEGIN TRY
DELETE #2;
END TRY
BEGIN CATCH
PRINT 1;
END CATCHCode Snippets
BEGIN TRANSACTION;
BEGIN TRY
DELETE #1;
DELETE #2;
DELETE #3;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCHBEGIN TRY
DELETE #1;
END TRY
BEGIN CATCH
PRINT 1;
END CATCH
BEGIN TRY
DELETE #2;
END TRY
BEGIN CATCH
PRINT 1;
END CATCHContext
StackExchange Database Administrators Q#23041, answer score: 27
Revisions (0)
No revisions yet.