分页存储过程(一)使用sql2005的新函数构造分页存储过程
|
其实在很多时候设计的度还是要把握的,不至于让自己陷入【非要把它设计成万能的分页存储过程】的怪圈中才是最重要的,因为我们还要留出时间还解决其他的很多问题,个人认为适度就可以了,留出一定的空间。也因为万能是不存在的,万物在一定的范畴之内都是合理的,出了范畴可能就没有合理的了。
C#中常用的分页存储过程小结 2005CTE,CTE http://www.cnblogs.com/nokiaguy/archive/2009/01/31/1381562.html
2005row_number(),rank,dense_rank,ntile
http://blog.csdn.net/htl258/archive/2009/03/20/4006717.aspx row_number()CTE Declare @totalRecord int; 存储过程SQL如下,支持不定列,不定条件,多表联合,排序任意 Enterprise Library 4.1 下载地址: http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&displaylang=en 示例代码,前台页面,前台为用户控件
EmptyDataText="没有符合条件的数据"> runat="server" /> '> '> '> '> '> '> 示例代码,后台代码 代码如下:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.Data; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using Kimbanx.UCS.ForeignStudentAdmin.Model; using Kimbanx.UCS.ForeignStudentAdmin.Common; namespace Kimbanx.UCS.ForeignStudentAdmin.UserControl.UserControl { public partial class StudentDetailsTable : System.Web.UI.UserControl { private Database _db = DatabaseFactory.CreateDatabase(); private DbCommand _command; private DbConnection _connection; private DataSet _ds; private string _classCode; private string _classFullName; private string _studentType; private string _studentCount; private string _queryStringWhere; private DataTable _studentTable; protected string SetBirthDate(object obj) { string result = string.Empty; string temp = obj.ToString(); result = DateTime.Parse(temp).ToShortDateString(); return result; } protected string SetEnrollDate(object obj) { string result = string.Empty; string temp = obj.ToString(); result = DateTime.Parse(temp).ToShortDateString(); return result; } protected void Filldata_dllPageSize() { for (int i = 1; i < 100; i++) { ddlPageSize.Items.Add(i.ToString()); } ddlPageSize.SelectedIndex = 14; } protected void InitSession() { //Session["PageSize"] = 0; Session["PageIndex"] = 1; Session["PageCount"] = int.Parse(_studentCount) / 15 + 1; } /// /// 获取QueryString传递参数 /// protected void GetQueryStringPara() { _classCode = Request.QueryString["dwbh"]; _classFullName =HttpUtility.UrlDecode( Request.QueryString["dwmc"]); _studentCount = Request.QueryString["studentCount"]; _studentType =HttpUtility.UrlDecode( Request.QueryString["studentType"]); _queryStringWhere = Request.QueryString["where"]; } protected void SetLabelText() { this.lblClassName.Text = _classFullName; this.lblClassLevel.Text = GetClassInfo(_classCode).Level.ToString(); this.lblStudentCount.Text = _studentCount; this.lblStudentType.Text = _studentType; } #region ///// ///// 获取学员数据 ///// ///// ///// ///// /// /// protected ClassEntity GetClassInfo(string classCode) { ClassEntity entity = new ClassEntity(); entity.Code = classCode; _command = _db.GetStoredProcCommand("ClassInfo"); _db.AddInParameter(_command,"bh",classCode); using (IDataReader reader = _db.ExecuteReader(_command)) { while (reader.Read()) { entity.FullName = reader.GetString(1); entity.Level = reader.GetInt32(2); } } return entity; } #region Get and Set PageSize protected int GetPageSize() { return int.Parse(ddlPageSize.SelectedValue); } protected void SetPageSize(int pageSize) { this.ddlPageSize.Text = pageSize.ToString(); } #endregion #region Get and Set PageIndex protected int GetPageIndex() { return int.Parse(this.lblPageIndex.Text.Trim()); } protected void SetPageIndex(int pageIndex) { this.lblPageIndex.Text = pageIndex.ToString(); } #endregion #region Get and Set PageCount protected int GetPageCount() { return int.Parse(this.lblPageCount.Text.Trim()); } protected void SetPageCount() { int studentCount = GetStudentCount(); int pageSize = GetPageSize(); if (studentCount % pageSize == 0) { this.lblPageCount.Text = (studentCount / pageSize).ToString(); } else { this.lblPageCount.Text = (studentCount / pageSize + 1).ToString(); } } #endregion #region Get and Set StudentCount protected int GetStudentCount() { return int.Parse(this.lblStudentCount.Text.Trim()); } protected void SetStudentCount(int studentCount) { this.lblStudentCount.Text = studentCount.ToString(); } #endregion protected void StudentCountZero() { this.lblPageIndex.Text = "0"; this.lblPageCount.Text = "0"; } protected void LinkButton_Command(object sender,CommandEventArgs e) { if (GetStudentCount() == 0) { StudentCountZero(); return; } int pageCount = GetPageCount(); int pageIndex = GetPageIndex(); int pageSize = GetPageSize(); switch (e.CommandArgument.ToString()) { case "first": if (pageIndex == 1) { } else { pageIndex = 1; SetPageIndex(pageIndex); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } break; case "next": if (pageCount == pageIndex & pageIndex == 1) { } else if (pageIndex == 1 && pageCount > pageIndex) { SetPageIndex(++pageIndex); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } else if (pageIndex > 1 && pageCount == pageIndex) { } else { SetPageIndex(++pageIndex); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } break; case "prev": if (pageIndex == 1) { } else if (pageIndex == pageCount && pageIndex > 1) { SetPageIndex(--pageIndex); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } else if (pageIndex == 2) { SetPageIndex(1); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } else { SetPageIndex(--pageIndex); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } break; case "last": if (pageCount == pageIndex) { } else { SetPageIndex(pageCount); pageIndex = GetPageIndex(); SetPageCount(); BindStudentData(pageSize,pageIndex); } break; default: SetPageIndex(1); pageSize = GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); break; } } protected void ddlPageSize_SelectedIndexChanged(object sender,EventArgs e) { int pageIndex = GetPageIndex(); int pageCount = GetPageCount(); int pageSize = GetPageSize(); pageIndex = 1; SetPageIndex(pageIndex); SetPageSize(int.Parse(((DropDownList)sender).SelectedValue)); pageSize=GetPageSize(); SetPageCount(); BindStudentData(pageSize,pageIndex); } } } 最后再贴一个圆友的通用存储过程,原文地址:通用存储过程分页(使用ROW_NUMBER()和不使用ROW_NUMBER()两种情况)性能分析 代码如下:set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go -- ============================================= -- Author: -- Create date: <2010-03-03> -- Description: -- 适合从单个表查询数据 -- ============================================= ALTER PROCEDURE [dbo].[Proc_GetDataPaged2] @tblName varchar(255),-- 表名如:'xtest' @strGetFields varchar(1000) = '*',-- 需要返回的列如:'xname,xdemo' @strOrder varchar(255)='',-- 排序的字段名如:'order by id desc' @strWhere varchar(1500) = '',-- 查询条件(注意:不要加where)如:'xname like ''%222name%''' @beginIndex int=1,--开始记录位置 --@pageIndex int = 1,-- 页码如:2 @pageSize int = 50,-- 每页记录数如:20 @recordCount int output,-- 记录总数 @doCount bit=0 -- 非0则统计,为0则不统计(统计会影响效率) AS declare @strSQL varchar(5000) declare @strCount nvarchar(1000) --总记录条数 if(@doCount!=0) begin if(@strWhere !='') begin set @strCount='set @num=(select count(1) from '+ @tblName + ' where '+@strWhere+' )' end else begin set @strCount='set @num=(select count(1) from '+ @tblName + ' )' end EXECUTE sp_executesql @strCount,N'@num INT output',@RecordCount output end if @strWhere !='' begin set @strWhere=' where '+@strWhere end set @strSQL='SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@strOrder+') AS ROWID,' set @strSQL=@strSQL+@strGetFields+' FROM ['+@tblName+'] '+@strWhere set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str(@beginIndex) set @strSQL=@strSQL+' AND '+str(@beginIndex+@PageSize) --set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) --set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) exec (@strSQL) 再来一个 代码如下:set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go -- ============================================= -- Author: -- Create date: -- Description: 分页获取商品信息 --调用方法: Proc_GetProductPaged '2','',0 -- ============================================= ALTER PROCEDURE [dbo].[Proc_GetProductPaged] -- Add the parameters for the stored procedure here @ProductType smallint=1,--商品类型,1全部2种子3农药4肥料 @StrSelect varchar(max)='',--显示字段 @StrFrom varchar(max)='',--查询来源 @StrWhere varchar(max)='',--查询条件 @StrOrder varchar(max)='',--排序规范 @PageSize int=50,--记录数 @BeginIndex int=1,--开始记录位置 -- @PageIndex int=1,--页码 @Count int output,--记录总数 @DoCount bit=0-- 1则统计,为0则不统计(统计会影响效率) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. declare @seedtype int set @seedtype=2 declare @pestype int set @pestype=3 declare @ferttype int set @ferttype=4 create table #product ( productid uniqueidentifier, productname varchar(50), className varchar(50), productType int, createdate datetime, modifydate datetime -- companyid uniqueidentifier ) declare @strSQL varchar(max) declare @strCount nvarchar(max) --计算总记录条数 if(@DoCount!=0) begin if(@StrWhere !='') begin if(@ProductType=1) begin set @strCount='set @num=(select count(1) from Seed where '+@StrWhere+' )'+ '+(select count(1) from pesticide where '+@StrWhere+' )'+ '+(select count(1) from fertilizer where '+@StrWhere+' )' end else if(@ProductType=2) begin set @strCount='set @num=(select count(1) from Seed where '+@StrWhere+' )' end else if(@ProductType=3) begin set @strCount='set @num=(select count(1) from pesticide where '+@StrWhere+' )' end else if(@ProductType=4) begin set @strCount='set @num=(select count(1) from fertilizer where '+@StrWhere+' )' end end else begin if(@ProductType=1) begin set @strCount='set @num=(select count(1) from Seed )'+ '+(select count(1) from pesticide )'+ '+(select count(1) from fertilizer )' end else if(@ProductType=2) begin set @strCount='set @num=(select count(1) from Seed )' end else if(@ProductType=3) begin set @strCount='set @num=(select count(1) from pesticide )' end else if(@ProductType=4) begin set @strCount='set @num=(select count(1) from fertilizer )' end end EXECUTE sp_executesql @strCount,@Count output end --分页获取数据 if (@StrWhere !='' ) begin set @StrWhere=' where '+@StrWhere end if(@ProductType=1) begin set @strSQL='insert into #product select s.seedid,s.seedname,cc.cropclassname,'+cast(@seedtype as varchar(1))+',s.createdate,s.modifydate from seed as s inner join cropclass as cc on s.cropclasscode=cc.cropclasscode' +@StrWhere+ 'union select p.pesticideid,p.pesname,pc.pesclassname,'+cast(@pestype as varchar(1))+',p.createdate,p.modifydate from pesticide as p inner join pesclass as pc on p.pesclasscode=pc.pesclasscode' +@StrWhere+ 'union select f.fertilizerid,f.fertname,fc.fertclassname,'+cast(@ferttype as varchar(1))+',f.createdate,f.modifydate from fertilizer as f inner join fertilizerclass as fc on f.fertclasscode=fc.fertclasscode' +@StrWhere set @strSQL= @strSQL+' SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@StrOrder+') AS ROWID,' set @strSQL=@strSQL+'* FROM [#product] '--+@StrWhere set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str(@BeginIndex) set @strSQL=@strSQL+' AND '+str(@BeginIndex+@PageSize-1) -- set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) -- set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) end else begin set @strSQL='insert into #product select '+@StrSelect+ ' from '+@StrFrom+@StrWhere exec (@strSQL) set @strSQL='' set @strSQL='SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@strOrder+') AS ROWID,' set @strSQL=@strSQL+'* FROM [#product]'+@strWhere set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str(@BeginIndex) set @strSQL=@strSQL+' AND '+str(@BeginIndex+@PageSize-1) -- set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) -- set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) end -- else if(@ProductType=2) -- begin -- set @strSQL='insert into #product select '+@StrSelect+','+@seedtype+ -- 'from '+@StrFrom+@StrWhere -- exec @strSQL -- set @strSQL='' -- set @strSQL='SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@strOrder+') AS ROWID,' -- set @strSQL=@strSQL+@StrSelect+' FROM[#product]'+@strWhere -- set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) -- set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) -- end -- else if(@ProductType=3) -- begin -- set @strSQL='SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@strOrder+') AS ROWID,' -- set @strSQL=@strSQL+@StrSelect+' FROM[#product]'+@StrWhere -- set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) -- set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) -- end -- else if(@ProductType=4) -- begin -- set @strSQL='SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@strOrder+') AS ROWID,' -- set @strSQL=@strSQL+@StrSelect+' FROM[#product]'+@StrWhere -- set @strSQL=@strSQL+') AS sp WHERE ROWID BETWEEN '+str((@PageIndex-1)*@PageSize+1) -- set @strSQL=@strSQL+' AND '+str(@PageIndex*@PageSize) -- end exec (@strSQL) drop table #product END (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
