A Program execution unit (unit) that accesses and may update various data items in a database consists of multiple SQL statements that must be executed as a whole
These SQL statements are submitted to the system as a whole, either executed or not executed
Syntax steps:
To start a transaction: Begin TRANSACTION--Open transaction
Transaction Commit: Commit TRANSACTION--commit action
Transaction rollback: ROLLBACK TRANSACTION--Cancel operation
--Build TableCREATE TABLE [ Person]([PersonId] NVARCHAR( -)PRIMARY KEY,---PRIMARY Key[PersonName] NVARCHAR( -)NULL)
/*if only begin TransAction and commit TransAction even error, it will not rollback the Select * from person*/Begin TransAction Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('3','Name3')Commit TransAction/*if only the begin TransAction and rollback TransAction have not been presented with an error, the Select * from person will be rolled back*/--Clear DataDelete PersonBegin TransAction Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('3','Name3')RollBack TransAction/*set XACT_ABORT on, in the event of an error in the transaction, the system rolls back the transaction by default, but only for non-custom errors valid SET Xact_abort OFF, default value, in the transaction, rollback of a statement or the entire transaction depending on the severity of the error program, user-level errors Errors generally do not roll back the entire transaction Select * from person*/SETXact_abort on --OpenBegin TransAction Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('3','Name3')Commit TransActionSETXact_abortOFF --Close/*Try Catch Mate transaction using Select * from person*/BeginTryBegin TransAction Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('1','Name1') Insert intoPerson (personid,personname)Values('3','Name3') Commit TransActionEndTryBeginCatchRollback TransActionEndCatch/*Use the global variable @ @Error mate transactions using Select * from person*/DECLARE @tran_error int;SET @tran_error = 0; Begin TransAction Insert intoPerson (personid,personname)Values('1','Name1') SET @tran_error = @tran_error + @ @ERROR; Print(@tran_error); Insert intoPerson (personid,personname)Values('1','Name1') SET @tran_error = @tran_error + @ @ERROR; Print(@tran_error); Insert intoPerson (personid,personname)Values('3','Name3') SET @tran_error = @tran_error + @ @ERROR; Print(@tran_error);IF(@tran_error > 0) BEGIN --performing an error, rolling back a transaction ROLLBACK TransAction; ENDELSE BEGIN --no exception, COMMIT transaction COMMIT TransAction; END
SQL Server Transactions