A transaction is one or more SQL statements that must be completed as a whole. Transactions provide a way of grouping multiple operations into a single all-or-nothing action. There are three types of transactions: autocommit transactions, explicit transactions defined using transaction control statements, and implicit transactions enabled by setting the implicit transactions session setting. Transactions ensure data integrity and consistency using the ACID properties - atomicity, consistency, isolation, and durability.
20. Explicit Transactions, Banking Transaction declare @source_account char(10), @destination_account char(10) select @source_account = ‘0003456321’, @destination_account = ‘0003456322’ BEGIN TRAN update account set balance = balance - $1000 where account_number = @source_account if @@error != 0 begin rollback tran return end update account set balance = balance + $1000 where account_number = @destination_account if @@error != 0 begin rollback tran return end commit tran
21. Explicit Transactions, Banking Transaction – Other Solution declare @source_account char(10), @destination_account char(10) select @source_account = ‘0003456321’, @destination_account = ‘0003456322’ BEGIN TRY Begin Transaction update account set balance = balance - $1000 where account_number = @source_account update account set balance = balance + $1000 where account_number = @destination_account Commit Transaction END TRY BEGIN CATCH RaiseError('Transaksinya Error Nich, Gimana ya? ', 1, 1, 1,1, 1, 1, 1 ); RollBack Transaction END CATCH
22.
23.
24.
25. SET IMPLICIT_TRANSACTIONS ON Go INSERT INTO table1 UPDATE table2 COMMIT Go SELECT * FROM table1 BEGIN TRAN DELETE FROM table1 COMMIT Go DROP TABLE table1 COMMIT
26. set implicit_transactions on Go Declare @source_account char(10), @destination_account char(10) select @source_account = ‘0003456321’, @destination_account = ‘0003456322’ UPDATE account set balance = balance - $1000 where account_number = @source_account if @@error != 0 begin rollback return End UPDATE account set balance = balance + $1000 where account_number = @destination_account if @@error != 0 begin rollback return end COMMIT
27.
28.
29. … CREATE TABLE testable (col1 int) go CREATE TABLE auditlog (who varchar(128), valuentered int null) go CREATE PROCEDURE trantest @arg INT AS BEGIN TRAN IF EXISTS( SELECT * FROM testable WHERE col1 = @arg ) BEGIN RAISERROR (‘Value %d already exists!’, 16, -1, @arg) ROLLBACK TRANSACTION END ELSE BEGIN INSERT INTO testable (col1) VALUES (@arg) COMMIT TRAN END INSERT INTO auditlog (who, valuentered) VALUES (USER_NAME(), @arg) return