--Transaction: is a processing mechanism, a processing method, is not an actual operation. All operations that are contained within a transaction that are likely to modify table data are either successfully executed or not executed.
--Transfer: Your account balance is reduced and the balance of your account is increased
--begin
--update Bank set cmoney-=1000 where name= ' AA '
--update Bank set cmoney+=1000 where name= ' BB '
--end
--print @ @error-just find the error number of the most recent statement
--the characteristics of the business: ACID:
--a: atomicity: A transaction is a whole that can no longer be divided
--c: Consistency: The data needs to be kept to a certain degree before and after the commit of the transaction
I: Isolation: Transactions are independent and unaffected by other transactions.
--d: Persistence: Once a transaction is committed, the data is permanently changed
--Transaction syntax:
--begin Transaction: Open transaction
--commit Transaction: Commit Transaction
--rollback transaction: Rolling back a transaction
--The way you use transactions: SQL commands that you need to process using the transaction mechanism are included in the opening and transaction commit of a transaction or transaction opening and transaction rollback
--using transactions to implement the transfer:
DECLARE @error int=0--The error number generated by the record statement
BEGIN TRANSACTION--open the business.
Update bank set cmoney-=500 where name= ' AA '
--You can never judge whether a transaction needs to be committed or rolled back when a SQL command is executed: 1. In this way, multiple SQL commands are no longer a whole 2. Other SQL commands are no longer included in the transaction and cannot be processed using the transaction mechanism. After each statement, use the variable to record the error number generated by the current statement.
--if (@ @ERROR <> 0)
--ROLLBACK TRANSACTION
Set @[email protected] @ERROR--Record the error number
Update bank set cmoney+=500 where name= ' BB '
Set @[email protected] @ERROR
--select * FROM Bank
--After all the statements have been executed, then unified to determine whether the transaction needs to be committed or rolled back
if (@error <>0)--there is an error
ROLLBACK TRANSACTION
Else
Commit TRANSACTION
---------------
Go
--Use transactions to implement transfers
DECLARE @error int=0--The error number generated by the record statement
BEGIN TRANSACTION--open the business.
Update bank set Cmoney-=500 where name = ' AA '
Set @error [email protected] @ERROR--Record the error number
Update bank set Cmoney +=500 where name = ' BB '
Set @error [email protected] @ERROR
--After all the statements have been executed, then unified to determine whether the transaction needs to be committed or rolled back
if (@error <>0)--there is an error
ROLLBACK TRANSACTION
Else
Commit TRANSACTION
-----------------------------
The transaction inside the SQL