存儲過程:
/**********************************
功能:根據一定條件讀取功能記錄
作者:rexsp
創建日期:2004-01-13
修改者:
修改日期:
**********************************/
alter procedure getscoresetting
( 
 @scoresettingid int=-1, ---設置id
 @functionid int=-1, ---功能id
 @operationid int=-1, ---操作id
 @roletypeid int=-1, ---角色類型
 @bbstypeid int=-1, ---版塊類型
 @score int=-1, ---積分設置 
 @bb int=-1, ---幣幣設置
 @buytype int=-1, ---購買類型 0:不是購買類型 1:一次性購買 2:反復購買
 @functionstate int=-1 ---功能狀態
)
as
set nocount on 
declare @strsql nvarchar(1000)
set @strsql = 'select * from [scoresetting] where @ckscoresettingid = @ckscoresettingid'
--- add keywords begin ---
if @scoresettingid<> -1
 begin
 set @strsql = @strsql + ' and scoresettingid= @ckscoresettingid'
 end
if @functionid<> -1
 begin
 set @strsql = @strsql + ' and functionid= @ckfunctionid'
 end
if @operationid<>-1
 begin
 set @strsql = @strsql + ' and operationid = @ckoperationid'
 end
if @roletypeid<>-1
 begin
 set @strsql = @strsql + ' and roletypeid = @ckroletypeid'
 end
if @bbstypeid<>-1
 begin
 set @strsql = @strsql + ' and bbstypeid = @ckbbstypeid'
 end
if @score<>-1
 begin
 set @strsql = @strsql + ' and score = @ckscore'
 end
if @bb<>-1
 begin
 set @strsql = @strsql + ' and bb= @ckbb'
 end
if @buytype<>-1
 begin
 set @strsql = @strsql + ' and buytype= @ckbuytype'
 end
if @functionstate<>-1
 begin
 set @strsql = @strsql + ' and functionstate= @ckfunctionstate'
 end
--- add where key word ---
--- run sql begin ---
execute sp_executesql @strsql,
 n' @ckscoresettingid int,
 @ckfunctionid int,
 @ckoperationid int,
 @ckroletypeid int,
 @ckbbstypeid int,
 @ckscore int,
 @ckbb int,
 @ckbuytype int,
 @ckfunctionstate int',
 @[email protected],
 @[email protected],
 @ckoperationid = @operationid,
 @ckroletypeid = @roletypeid,
 @ckbbstypeid = @bbstypeid,
 @ckscore = @score,
 @ckbb = @bb,
 @ckbuytype = @buytype,
 @ckfunctionstate = @functionstate
--- run sql end ---
 
一點說明:
此存儲過程會根據數據層的類有沒有傳遞相應的參數值進來而動態創建查詢語句,然后用系統自帶的存儲過程執行sql語句,用系統存儲過程執行sql語句的好處是可以自動轉義字符。而動態創建查詢語句的好處,就非常大了,這會省下我們寫很多種條件判斷,尤其是對那些字段比較多的表來講,一個排列組合下來的情況太多了,而利用存儲過程動態創建sql語句所作的判斷數和字段數基本上是一致的,這里會給入參賦初始值,如果不等于初始值就說明數據層類有傳遞參數進來,這樣就加上相應條件字符的查詢條件。