天天看點

機房收費系統總結之7——存儲過程

        效率是每個人追求的目标,其中在資料庫中特别能展現效率的對象就是——存儲過程。

        一、定義

        将常用的或很複雜的工作,預先用SQL語句寫好并用一個指定的名稱存儲起來,那麼以後要叫資料庫提供與已定義好的存儲過程的功能相同的服務時,隻需調用execute,即可自動完成指令。

        二、優點

        1.存儲過程隻在創造時進行編譯,以後每次執行存儲過程都不需再重新編譯,而一般SQL語句每執行一次就編譯一次,是以使用存儲過程可提高資料庫執行速度。 

        2.當對資料庫進行複雜操作時(如對多個表進行Update,Insert,Query,Delete時),可将此複雜操作用存儲過程封裝起來與資料庫提供的事務處理結合一起使用。

        3.存儲過程可以重複使用,可減少資料庫開發人員的工作量

        4.安全性高,可設定隻有某此使用者才具有對指定存儲過程的使用權

        三、舉例

        機房收費系統中,像結賬部分,就會涉及多張表,就可以直接把那些操作步驟集合在一個存儲過程中。

先看存儲過程中的代碼

-- =============================================
-- Author:	張連海
-- Create date: 2013.10.05
-- Description:	完成結賬時,對資料庫的一系列操作
-- =============================================
Create  procedure [dbo].[Proc_SettleAccounts]
	@operateUserName varchar(20),		--操作員的使用者名
	@isSettleAccounts varchar(10),		--結賬狀态
	@settleAccountsResult varchar(10)	--結賬後的結果
as
begin
	update T_Register set isSettleAccounts [email protected] where regUser [email protected] and isSettleAccounts [email protected]
	update T_AbsentCard set isSettleAccounts [email protected] where abCardUser [email protected] and isSettleAccounts [email protected]
	update T_Recharge set isSettleAccounts [email protected] where recUser [email protected] and isSettleAccounts [email protected]
end
           

        再看系統中D層代碼(其他部分就略了)

Public Function UpdateAccounts(ByVal enUserInfo As UserInfoEntity) As Integer Implements ISettleAccounts.UpdateAccounts
    '聲明并執行個體化存儲過程
    Dim strProc As String = "Proc_SettleAccounts"

    '聲明并執行個體化參數資料
    Dim sqlParams As SqlParameter() = {New SqlParameter("@operateUserName", enUserInfo.UserName),
                                        New SqlParameter("@isSettleAccounts", "未結賬"),
                                        New SqlParameter("@settleAccountsResult", "已結賬")}

    '執行并傳回查詢結果
    Return clsSqlHelper.ExecAddDelUpdate(strProc, CommandType.StoredProcedure, sqlParams)
End Function
           

        這就是存儲過程,通過親自初嘗實踐,感覺不算很難。嘿嘿!

繼續閱讀