榴莲的味道

年轻人的Blog,欢迎您!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Sqlserver存储过程和C#分页类简化你的代码!(精华)

Posted on 2006-09-26 09:01  刘建锋  阅读(210)  评论(0)    收藏  举报

在最近的项目中,由于要用到自定义分页的功能,本人就在网上找了个存储过程。结合C#写了个分页类。由于本人第一次写文章。写得不好,大家不要扔鸡蛋。。

下面是存储过程(sqlserver2000下通过)

 

--最通用的分页存储过程
--
 获取指定页的数据 

CREATE PROCEDURE Pagination 

@tblName   varchar(255),       -- 表名 

@strGetFields varchar(1000= '*',  -- 需要返回的列 

@fldName varchar(255)='',      -- 排序的字段名 

@PageSize   int = 10,          -- 页尺寸 

@PageIndex  int = 1,           -- 页码 

@doCount  bit = 0,   -- 返回记录总数, 非 0 值则返回 

@OrderType bit = 0,  -- 设置排序类型, 非 0 值则降序 

@strWhere  varchar(1500= ''  -- 查询条件 (注意: 不要加 where) 

AS 

declare @strSQL   varchar(5000)       -- 主语句 

declare @strTmp   varchar(110)        -- 临时变量 

declare @strOrder varchar(400)        -- 排序类型 



if @doCount != 0 

 
begin 

   
if @strWhere !='' 

   
set @strSQL = 'select count(*) as Total from ['+ @tblName +'] where '+ @strWhere 

   
else 

   
set @strSQL = 'select count(*) as Total from ['+ @tblName +']'

end 

--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都
--
是@doCount为0的情况 

else 

begin 



if @OrderType != 0 

begin 

   
set @strTmp = '<(select min' 

set @strOrder = ' order by ['+ @fldName +'] desc'

--如果@OrderType不是0,就执行降序,这句很重要! 

end 

else 

begin 

   
set @strTmp = '>(select max'

   
set @strOrder = ' order by ['+ @fldName +'] asc'

end 



if @PageIndex = 1 

begin 

   
if @strWhere != ''   

    
set @strSQL = 'select top ' + str(@PageSize+' '+@strGetFields+ '  from ['+ @tblName +'] where ' + @strWhere + ' ' + @strOrder 

    
else 

    
set @strSQL = 'select top ' + str(@PageSize+' '+@strGetFields+ '  from ['+ @tblName +''+ @strOrder 

--如果是第一页就执行以上代码,这样会加快执行速度 

end 

else 

begin 

--以下代码赋予了@strSQL以真正执行的SQL代码 

set @strSQL = 'select top ' + str(@PageSize+' '+@strGetFields+ '  from [' + @tblName +'] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) 
from (select top 
' + str((@PageIndex-1)*@PageSize+ ' ['+ @fldName + '] from ['+ @tblName +']' + @strOrder + ') as tblTmp)'+ @strOrder 



if @strWhere != '' 

   
set @strSQL = 'select top ' + str(@PageSize+' '+@strGetFields+ '  from ['+ @tblName +'] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize+ ' ['+ @fldName + '
from [
'+ @tblName +'] where ' + @strWhere + ' ' + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder 

end 

end   

exec ( @strSQL)
GO

 

下面是C#的代码

 

 

  1using System.Data ; 
  2using System.Data.SqlClient ; 
  3using Microsoft.ApplicationBlocks.Data ; 
  4using System.Web ; 
  5using System.Web.UI ; 
  6namespace RssLayer.PageHelper 
  7
  8    /// <summary> 
  9    /// 分页类PagerHelper 的摘要说明。 
 10    /// </summary> 

 11    public class PagerHelper 
 12    
 13        private string connectionString; 
 14 
 15     
 16 
 17        public PagerHelper(string tblname,string sortname,bool docount,string connectionString) 
 18        
 19            this.tblName = tblname; 
 20            this.fldName = sortname ; 
 21            this.connectionString  = connectionString ; 
 22            this.docount = docount; 
 23        }
 
 24 
 25        public PagerHelper(string tblname,bool docount, 
 26            string strGetFields,    string fldName,int pagesize, 
 27            int pageindex,bool ordertype,string strwhere,string connectionString         
 28            ) 
 29        
 30            this.tblName = tblname ;             
 31            this.docount = docount ; 
 32            this.strGetFields = strGetFields ; 
 33            this.fldName = fldName; 
 34            this.pagesize = pagesize ; 
 35            this.pageindex = pageindex; 
 36            this.ordertype = ordertype ; 
 37            this.strwhere = strwhere ; 
 38            this.connectionString  = connectionString ; 
 39 
 40        }
 
 41 
 42 
 43    /// <summary> 
 44        /// 得到记录集的构造函数 
 45        /// </summary> 
 46        /// <param name="tblname"></param> 
 47        /// <param name="strwhere"></param> 
 48        /// <param name="connectionString"></param> 

 49        public PagerHelper(string tblname,string strwhere,string connectionString)     
 50        
 51            this.tblName = tblname; 
 52            this.strwhere = strwhere ; 
 53            this.docount = true
 54            this.connectionString  = connectionString ; 
 55        }
 
 56 
 57        private string tblName; 
 58        public string TblName 
 59        
 60            get{return tblName;} 
 61            set{tblName =value;} 
 62        }
 
 63 
 64        private string strGetFields="*"
 65        public string StrGetFields 
 66        
 67            get{return strGetFields ;} 
 68            set{strGetFields =value;} 
 69        }
 
 70 
 71        private string fldName=string.Empty; 
 72        public string FldName 
 73        
 74            get{return fldName ;} 
 75            set{fldName =value;} 
 76        }
 
 77 
 78         
 79 
 80        private int pagesize =10
 81        public int PageSize 
 82        
 83            get{return pagesize ;} 
 84            set{pagesize =value;} 
 85        }
 
 86 
 87        private int pageindex =1
 88        public int PageIndex 
 89        
 90            get{return pageindex ;} 
 91            set{pageindex =value;} 
 92        }
 
 93 
 94 
 95        private bool docount=false
 96        public bool DoCount 
 97        
 98            get{return docount ;} 
 99            set{docount =value;} 
100        }
 
101 
102        private bool ordertype=false
103        public bool OrderType 
104        
105            get{return ordertype ;} 
106            set{ordertype =value;} 
107        }
 
108 
109        private string strwhere=string.Empty ; 
110        public string StrWhere 
111        
112            get{return strwhere ;} 
113            set{strwhere =value;} 
114        }
 
115 
116         
117 
118 
119     
120 
121        public IDataReader GetDataReader() 
122        
123 
124            if(this.docount) 
125            
126                throw new ArgumentException("要返回记录集,DoCount属性一定为false"); 
127            }
 
128 
129         
130 
131        //    System.Web.HttpContext.Current.Response.Write(pageindex); 
132 
133            return SqlHelper.ExecuteReader(connectionString,CommandType.StoredProcedure,"Pagination"
134                new SqlParameter("@tblName",this.tblName), 
135                new SqlParameter("@strGetFields",this.strGetFields), 
136                new SqlParameter("@fldName",this.fldName), 
137                new SqlParameter("@PageSize",this.pagesize), 
138                new SqlParameter("@PageIndex",this.pageindex), 
139                new SqlParameter("@doCount",this.docount), 
140                new SqlParameter("@OrderType",this.ordertype), 
141                new SqlParameter("@strWhere",this.strwhere) 
142                ); 
143        }
 
144 
145        public DataSet GetDataSet() 
146        
147            if(this.docount) 
148            
149                throw new ArgumentException("要返回记录集,DoCount属性一定为false"); 
150            }
     
151 
152            return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure,"Pagination"
153                new SqlParameter("@tblName",this.tblName), 
154                new SqlParameter("@strGetFields",this.strGetFields), 
155                new SqlParameter("@fldName",this.fldName), 
156                new SqlParameter("@PageSize",this.pagesize), 
157                new SqlParameter("@PageIndex",this.pageindex), 
158                new SqlParameter("@doCount",this.docount), 
159                new SqlParameter("@OrderType",this.ordertype), 
160                new SqlParameter("@strWhere",this.strwhere) 
161                ); 
162        }
 
163 
164 
165        public int GetCount() 
166        
167            if(!this.docount) 
168            
169                throw new ArgumentException("要返回总数统计,DoCount属性一定为true"); 
170            }
 
171 
172                     
173 
174            return (int)SqlHelper.ExecuteScalar(connectionString,CommandType.StoredProcedure,"Pagination"
175                new SqlParameter("@tblName",this.tblName), 
176                new SqlParameter("@strGetFields",this.strGetFields), 
177                new SqlParameter("@fldName",this.fldName), 
178                new SqlParameter("@PageSize",this.pagesize), 
179                new SqlParameter("@PageIndex",this.pageindex), 
180                new SqlParameter("@doCount",this.docount), 
181                new SqlParameter("@OrderType",this.ordertype), 
182                new SqlParameter("@strWhere",this.strwhere) 
183                ); 
184        }
         
185 
186    }
 
187 
188     
189 
190 
191}
 
192

如何调用???

假如我已经建立了2个类。一个是FavList数据库实体类,一个FavListCollection集合类。FavListCollection存储了FavList实体类的集合。

我可以这样写一个方法。

 /// <summary>
        
/// 返回FavList集合,使用存储过程自定义分页。
        
/// </summary>
        
/// <param name="userid">数据库FavList的字段,用户ID</param>
        
/// <param name="strwhere">查找的条件</param>
        
/// <param name="ordertype">排序,true表示Desc,false表示asc</param>
        
/// <param name="fldname">排序的字段,只能是一个字段</param>
        
/// <param name="pagesize">每页的记录数</param>
        
/// <param name="pageindex">到第几页的参数,由1开始。1表示第一页,以此类推。</param>
        
/// <param name="recordcount">总记录数。</param>
        
/// <returns></returns>

        public override FavListCollection GetFavListsByUser(int userid, string strwhere, 
            
bool ordertype, string fldname, int pagesize,
            
int pageindex,out int recordcount
            )
        
{
            recordcount 
= 0;
            PagerHelper helper 
= new PagerHelper("Vfavlist",strwhere,ConnectionString); //VFavList是View
            recordcount 
= helper.GetCount();
            
            PagerHelper helper2 
= new PagerHelper("Vfavlist",false," * ",fldname,
                pagesize,pageindex,ordertype,strwhere,ConnectionString);

            IDataReader dr 
= helper2.GetDataReader();

            FavListCollection list 
= new FavListCollection();
        
            
while(dr.Read())
            
{
                list.Add(PopulateFavList(dr));
            }


            dr.Close();

            
return list;
        }

DataGrid调用就不用说了吧。。

关于该分页的Bug和局限性

Bug:当排序那个字段内容相同的时候(例如:按时间来排序,而时间是一样的话。后面的记录会显示不出来。本人测试过)

局限性:排序只能一个字段,不能超过一个

 

如有问题:可以回帖