devxlogo

Use SQL Server Savepoints Intelligently

Use SQL Server Savepoints Intelligently

You can use savepoints in rolling back portions of transactions to predefined locations. A T-SQL savepoint defines a location to which a transaction can return if part of the transaction is conditionally canceled.

Keep in mind that SQL updates and rollbacks generally are expensive operations. So savepoints are useful only in situations where errors are unlikely and checking the validity of an update beforehand is relatively costly.

The syntax for typical server savepoint usage (where SAVE TRANSACTION permissions default to any valid user) is:

 SAVE TRANSACTION SavepointNameIF @@error= some ErrorBEGIN    ROLLBACK TRANSACTION SavepointNameCOMMIT TRANSACTIONEND

A word to the wise: whenever you roll back a transaction to a savepoint, it must proceed to completion or be canceled altogether. Therefore a COMMIT or a complete ROLLBACK should always follow a rollback to savepoint, because the resources used during the transaction (namely the SQL locks) are held until the completion of the transaction. When part of a transaction rolls back to a savepoint, resources continue to be held until either the completion of the transaction or a rollback of the complete transaction. In other words, even after rollback to a midpoint, the transaction is considered open and must be closed by either committing work or rolling back the entire transaction.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist