SQL 函數:事務執行個體

來源:互聯網
上載者:User

事務就是負責把一系列操作看做一個獨立的邏輯單元,這些操作要麼同時成功,要麼同時失敗。下面是一個經典的例子:

create
 
procedure
 TransferMoeny
(
    
@FromAccountNo
 
varchar
(
50
),
--
 轉出帳號


    
@ToAccountNo
 
varchar
(
50
),
--
轉入帳號


    
@MoneyCount
 
money
--
轉賬金額


)

as


--
判斷帳號是否存在


if
 
exists
 (
select
 
1
 
from
 帳戶表 
where
 帳號 
=
 
@FromAccountNo
) 

begin

    
if
 
exists
 (
select
 
1
 
from
 帳戶表 
where
 帳號 
=
 
@ToAccountNo
) 
    
begin

        
--
判斷轉出金額是否大於當前餘額


        
if
 (
select
 當前餘額 
from
 帳戶表 
where
 帳號 
=
 
@FromAccountNo
) 
>=
 
@MoneyCount

        
begin

            
--
開始轉賬


            
begin
 
transaction

            
insert
 
into
 
[
存取記錄表
]
 (
[
帳號
]
,
[
存取類型
]
, 
[
存取金額
]
) 
values
(
@FromAccountNo
, 
-
1
,
@MoneyCount
)
            
if
 
@@error
 
<>
 
0

            
begin

                
rollback
 
transaction
--
發生錯誤則復原事務,無條件退出l


                
return

            
end

                       
insert
 
into
 
[
存取記錄表
]
 (
[
帳號
]
,
[
存取類型
]
, 
[
存取金額
]
) 
values
(
@ToAccountNo
, 
1
,
@MoneyCount
)
            
if
 
@@error
 
<>
 
0

            
begin

                
rollback
 
tran

                
return

            
end

            
commit
 
transaction
 
--
兩條語句都完成,提交事務


        
end

        
else
    
            
raiserror
 (
'
轉賬金額不能大於該帳號的餘額
'
,
16
,
1
)
    
end

    
else

    
raiserror
 (
'
轉入帳號不存在
'
,
16
,
1
)


end


else

    
raiserror
 (
'
轉出帳號不存在
'
,
16
,
1
)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.