how does XACTABORT work for a sql server script? if I have a script that does some…
- User
how does XACT_ABORT work for a sql server script? if I have a script that does some select queries and some delete queries (the delete queries are inside a "sql transaction" - I did this so that if some delete queries fail, the successful ones won't get committed), do I need to set XACT_ABORT on or off? does XACT_ABORT only apply to the sql transaction or all of the script? if it applies to just a sql transaction, how do I specify which sql transaction to turn it on for? do the deletes need a sql transaction in the first place?
- Assistant
XACT_ABORTis a SQL Server setting that, when set to ON, automatically rolls back the current transaction if a run-time error occurs. It works at the transaction level and not for individual statements inside the transaction. If there is an error within the transaction, it will rollback the entire transaction and won't affect any statement outside the transaction.In your case, since you are using transactions for your
DELETEqueries, you can useXACT_ABORTto ensure that your transaction is rolled back if any of theDELETEqueries fail. You don't need to turn it on and off for individual transactions. Instead, it will affect all transactions in the current session. To enable it, simply add at the beginning of your script: - User
do I need to set XACT_ABORT to OFF at the end off the script or will it not matter due to scope? what about using a try/catch outside a transaction instead of XACT_ABORT ?
- Assistant
If you set
XACT_ABORTto ON at the beginning of your script and want to revert it to the previous setting when your script finishes, you can addSET XACT_ABORT OFF;at the end of your script. However, in most cases, it's sufficient to set it to ON if required, and you don't need to revert it at the end, as the setting will only apply to your current session, and other sessions will have their own separate settings. If you're concerned about preserving the original setting, you can store the current setting in a variable and restore it at the end of the script:DECLARE @original_xact_abort_setting AS VARCHAR(3); SELECT @original_xact_abort_setting = CONVERT(VARCHAR(3), @@OPTIONS & 16384); SET XACT_ABORT ON; -- Your queries and transactions go here IF @original_xact_abort_setting = '0' SET XACT_ABORT OFF;