The following is how you would wrap a transaction around a DELETE statement:
The above query will only execute if there are no errors, if there's an error the transaction will be rolled back. That's it, that's the whole concept of what a transaction is, if there are no errors then you should get the following message.
BEGIN TRANSACTION
DELETE Products WHERE ProductID = 87
COMMIT TRANSACTION
(1 row(s) affected)
If you are dealing with multiple statements then you can use the SAVE TRANSACTION, SAVE TRANSACTION allows you to create a placeholder so that you can rollback a transaction at a checkpoint.
For example if you were to INSERT a new order you would need to insert a new record into the Customers table and then the Orders table and then the OrderDetails table. You wouldn't want to rollback the whole transaction if something goes wrong. You might want to record the customer who tries to order your product, but couldn't and then have your customer representative do a follow up to complete the transaction if something goes wrong.
Here is how you would do a partial rollback:
The above query rolls back the query if there's an error. Notice the IF @@Error condition.
BEGIN TRANSACTION
INSERT INTO Customers(CustomerID,CompanyName)
VALUES ('ACME','ACME Company')
SAVE TRANSACTION StartOrder
INSERT INTO Orders(OrderID,CustomerID)
VALUES (10999,'ACME')
IF @@Error <> 0 ROLLBACK TRANSACTION StartOrder
INSERT INTO [Order Details](OrderID,ProductID,UnitPrice,Quantity,Discount)
VALUES (10999,14,23.25,1,0)
COMMIT TRANSACTION
=
No comments:
Post a Comment