存储过程:
/**********************************
功能:根据一定条件读取功能记录
作者: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语句所作的判断数和字段数基本上是一致的,这里会给入参赋初始值,如果不等于初始值就说明数据层类有传递参数进来,这样就加上相应条件字符的查询条件。