銀行轉賬存儲過程
USE [BankInfor] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[Transfer](@inAccount int,@outAccount int,@amount float) as declare @totalDeposit float; begin select @totalDeposit=total from Account where AccountNum=@outAccount; if @totalDeposit is null begin rollback; print'轉出賬戶不存在或賬戶中沒有存款' return; end if @totalDeposit<@amount begin rollback; print'余額不足,不能操作' return; end update Account set total=total-@amount where AccountNum=@outAccount; update Account set total=total+@amount where AccountNum=@inAccount; print'轉賬成功!' commit; end;
流水號生成存儲過程
if exists(select 1 from sysobjects where id=OBJECT_ID('GetSerialNo') and xtype='p') drop proc GetSerialNo go Create procedure [dbo].[GetSerialNo] ( @sCode varchar(50) ) as begin Declare @sValue varchar(16),@dToday datetime,@sQZ varchar(50) --這個代表前綴 Begin Tran Begin Try -- 鎖定該條記錄,好多人用lock去鎖,起始這裡只要執行一句update就可以了 --在同一個事物中,執行了update語句之後就會啟動鎖 Update SerialNo set sValue=sValue where sCode=@sCode Select @sValue = sValue From SerialNo where sCode=@sCode Select @sQZ = sQZ From SerialNo where sCode=@sCode -- 因子表中沒有記錄,插入初始值 If @sValue is null Begin Select @sValue = convert(bigint, convert(varchar(6), getdate(), 12) + '000001') Update SerialNo set sValue=@sValue where sCode=@sCode end else Begin --因子表中沒有記錄 Select @dToday = substring(@sValue,1,6) --如果日期相等,則加1 If @dToday = convert(varchar(6), getdate(), 12) Select @sValue = convert(varchar(16), (convert(bigint, @sValue) + 1)) else --如果日期不相等,則先賦值日期,流水號從1開始 Select @sValue = convert(bigint, convert(varchar(6), getdate(), 12) +'000001') Update SerialNo set sValue =@sValue where sCode=@sCode End Select result = @sQZ+@sValue Commit Tran End Try Begin Catch Rollback Tran Select result = 'Error' End Catch end select*from SerialNo select convert(varchar(6), getdate(), 12)+'000001'