Transaction
- First, what is a business
Code control that ensures consistency of data, either committing commits or rolling back to the initial state of a transaction
- Second, the four characteristics of business: ACID
A: atomicity-------transaction is not detachable, either executed or rolled back without intermediate state
C: Consistency-------consistency before and after data
I: Isolation-------transactions are not allowed to interfere in the course of execution
D: Possession-------exist on the hard drive
Start transaction: BEGIN TRANSACTION or BEGIN TRAN or start transaction [transaction name]
Commit TRANSACTION: commit[Transaction name]
ROLLBACK TRANSACTION: Rollback
@ @error: Returns the error code of the previous SQL statement, no error returned 0
For example:
Method One: Use @ @ERROR and if to determine using transactions
Declare @t int --record the accumulated error messageSet @t = 0begin Tran --Start a transactionInsert intoInfoValues('p003','吴倩','0','n004','1990-8-12')Set @t = @t +@ @ERROR --Cumulative error messageInsert intoInfoValues('p006','Zhang San','1','n004','1992-3-19')Set @t = @t +@ @ERROR --Cumulative error messageInsert intoInfoValues('p005','John Doe','0','n001','1991-12-24')Set @t = @t +@ @ERROR --Cumulative error messageif @t<> 0 --Roll back if errors are found in the accumulationbegin rollbackEndElse --If no errors are found in the accumulation, submitbegin CommitEnd
Law II: Use Try...catch .... To use transactions
-- Try...catch .... Statement begin Try ... -- execute the statement here without error End Try begin catch ... -- If an error occurs, execute the statement here End Catch
begin TranbeginTryInsert intoInfoValues('p007','Harry','0','n002','1991-4-1') Insert intoInfoValues('p009','Zhang Si','1','n004','1992-3-19') Insert intoInfoValues('p008','Li Nine','0','n001','1991-12-24') CommitEndTrybeginCatchrollbackEndCatch
Other methods: You can nest transactions by using the IF statement
SQL database-<...> transactions--Simple learning