SQL function: Transaction instance

Source: Internet
Author: User

A transaction is responsible for taking a series of operations as an independent logical unit. These operations either succeed or fail at the same time. The following is a classic example:

Create
 
Procedure
TransferMoeny
(

@ FromAccountNo
 
Varchar
(
50
),
--
Transfer Account



@ ToAccountNo
 
Varchar
(
50
),
--
Transfer Account



@ MoneyCount
 
Money
--
Transfer amount


)

As


--
Determine whether the account exists


If
 
Exists
(
Select
 
1
 
From
Account table
Where
Account
=
 
@ Fromaccountno
)

Begin


If
 
Exists
(
Select
 
1
 
From
Account table
Where
Account
=
 
@ Toaccountno
)

Begin


--
Determine whether the transfer amount is greater than the current balance



If
(
Select
Current Balance
From
Account table
Where
Account
=
 
@ FromAccountNo
)
> =
 
@ MoneyCount


Begin


--
Start Transfer



Begin
 
Transaction


Insert
 
Into
 
[
Access record table
]
(
[
Account
]
,
[
Access type
]
,
[
Access amount
]
)
Values
(
@ Fromaccountno
,
-
1
,
@ Moneycount
)

If
 
@ Error
 
<>
 
0


Begin


Rollback
 
Transaction
--
If an error occurs, roll back the transaction and exit unconditionally.



Return


End


Insert
 
Into
 
[
Access record table
]
(
[
Account
]
,
[
Access type
]
,
[
Access amount
]
)
Values
(
@ Toaccountno
,
1
,
@ Moneycount
)

If
 
@ Error
 
<>
 
0


Begin


Rollback
 
Tran


Return


End


Commit
 
Transaction
 
--
Both statements are completed and the transaction is committed.



End


Else


Raiserror
(
'
The transfer amount cannot exceed the account balance
'
,
16
,
1
)

End


Else


Raiserror
(
'
The transfer account does not exist.
'
,
16
,
1
)


End


Else


Raiserror
(
'
The outbound account does not exist.
'
,
16
,
1
)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.