分頁存儲過程大致有下列幾種
1、 利用Not in 和select top
2、 利用id大於多少和select top
3、 利用sql中的游標
4、臨時表
可以參看網上的以下鏈接
C#中常用的分頁存儲過程小結
http://read.newbooks.com.cn/info/174545.html
在2005中我們的選擇就多了,可以利用新語法CTE(公用表表達式),關於CTE的介紹大家可以參看博客園中一位仁兄的系列教程
http://www.cnblogs.com/nokiaguy/archive/2009/01/31/1381562.html
或者干脆上微軟的官網
http://msdn.microsoft.com/zh-cn/library/ms190766(SQL.90).aspx
查看具體內容。
除此之外還可以利用在2005中新增的一些函數,分別是:row_number(),rank,dense_rank,ntile,這些新函數是您可以有效的分析數據以及向查詢餓結果行提供排序值。您可能發現這些新函數有用的典型方案包括:將連續整數分配給結果行,以便進行表示、分頁、計分和繪制直方圖。
詳細介紹參見下列鏈接
http://blog.csdn.net/htl258/archive/2009/03/20/4006717.aspx
我這裡主要使用的就是row_number()結合新語法CTE,先貼上我的存儲過程。設計,開發,測試存儲過程和相關的C#代碼就花費我兩天的時間,不過後面的相似界面就很快了,一上午就可以搞兩個分頁顯示的頁面,就算是復雜的查詢,一上午也可以搞定。
下面的存儲過程沒有將總頁數和總條目數返回,如果你有興趣,可以自己加上,可以參看 C#中常用的分頁存儲過程小結中的下列部分
Declare @sql nvarchar(4000);
Declare @totalRecord int;
--計算總記錄數
if (@SqlWhere ='''' or @SqlWhere='' or @sqlWhere is NULL)
set @sql = 'select @totalRecord = count(*) from ' + @TableName
else
set @sql = 'select @totalRecord = count(*) from ' + @TableName + ' where ' + @sqlWhere
EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT--計算總記錄數
--計算總頁數
select @TotalPage=@totalRecord --CEILING((@totalRecord+0.0)/@PageSize)
存儲過程SQL如下,支持不定列,不定條件,多表聯合,排序任意
復制代碼 代碼如下:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
--Declare @sql nvarchar(4000);
--Declare @totalRecord int;
----計算總記錄數
--if (@SqlWhere ='''' or @SqlWhere='' or @sqlWhere is NULL)
--set @sql = 'select @totalRecord = count(*) from ' + @TableName
--else
--set @sql = 'select @totalRecord = count(*) from ' + @TableName + ' where ' + @sqlWhere
--EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT--計算總記錄數
--
----計算總頁數
--
--select @TotalPage=@totalRecord --CEILING((@totalRecord+0.0)/@PageSize)
-- =============================================
-- Author: shiwenbin
-- MSN: [email protected]
-- Email: [email protected]
-- Create date: 2009-10-20
-- Description: 分頁存儲過程,根據傳遞的參數返回分頁的結果
-- Parameters:
-- =============================================
ALTER PROCEDURE [dbo].[Proc_GetDataPaged]
-- Add the parameters for the stored procedure here
@StrSelect varchar(max)=null, --欲顯示的列(多列用逗號分開),例如:id,name
@StrFrom varchar(max)= null, --表名稱,或者是表連接字符串,多表連接例如:student as s inner join dwinfo as dw on s.dwbh=dw.bh
@StrWhere varchar(max)=null, --查詢條件,''代表沒有條件,單條件或者多條件,多條件例如:name='啊' and id=10
@StrOrder varchar(max) =null, --排序列(多個排序列用逗號分開),例如:id desc,name as
--@PageCount int output, --總頁數
@ItemCount bigint output, --總記錄數
@PageSize int =50, --每頁顯示條數
@BeginIndex int=1,--記錄開始數
@DoCount bit =0 --是否統計總數,為0不統計,為1統計
-- @PageIndex int =1 --當前頁
--@ClassCode char(10) =null, --單位編號(班級編號)
AS
BEGIN
SET NOCOUNT ON;
Declare @sql nvarchar(4000);
Declare @totalRecord int;
--計算總記錄數
if (@StrWhere ='''' or @StrWhere='' or @StrWhere is NULL)
set @sql = 'select @totalRecord = count(*) from ' + @StrFrom
else
set @sql = 'select @totalRecord = count(*) from ' + @StrFrom + ' where ' + @StrWhere
EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@ItemCount OUTPUT--計算總記錄數
declare @SqlQuery varchar(max)
-- if(@PageIndex=1)
if(@BeginIndex=1 or @BeginIndex=0 or @BeginIndex <0)
begin
if(@StrWhere is null)--if(@StrWhere='')
set @SqlQuery='select top '+convert(varchar,@PageSize)
+ ' row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+
' from '+@StrFrom;
else
--set @sql='select top @PageSize * from @TableName order by id desc';
--select top @PageSize * from @TableName order by id desc;
set @SqlQuery='select top '+convert(varchar,@PageSize)
+ ' row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+' where '+@StrWhere;
--exec (@SqlQuery)
-- @SqlQuery
end
else
begin
if(@StrWhere is null)--if(@StrWhere='')
begin
set @SqlQuery='with cte as (
select row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+'
)
select * from cte where RowNumber between '+
--convert(varchar,((@PageIndex-1)*@PageSize)+1)+' and '+
--
-- convert(varchar,@PageIndex*@PageSize)
convert(varchar,@BeginIndex)+' and '+
convert(varchar,@BeginIndex+@PageSize)
--print @SqlQuery
end
else
begin
set @SqlQuery='with cte as (
select row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+' where '+@StrWhere+'
)
select * from cte where RowNumber between '+
--convert(varchar,((@PageIndex-1)*@PageSize)+1)+' and '+
--
-- convert(varchar,@PageIndex*@PageSize)
convert(varchar,@BeginIndex)+' and '+
convert(varchar,@BeginIndex+@PageSize)
--print @SqlQuery
end
end
--set @SqlQuery=@SqlQuery+';select @ItemCount =count(*) from '+@TableName
--set @PageCount=@ItemCount/@PageSize
--print '共'+@PageConut+'頁'+@ItemCount+'條'
--print @ItemCount
print @SqlQuery
exec (@SqlQuery)
END
c#相關代碼的數據庫訪問使用的是微軟的企業庫 V4.1
Enterprise Library 4.1 下載地址:
http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&displaylang=en
示例代碼,前台頁面,前台為用戶控件
復制代碼 代碼如下:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="StudentDetailsTable.ascx.cs" Inherits="Kimbanx.UCS.ForeignStudentAdmin.UserControl.UserControl.StudentDetailsTable" %>
<link href="../css/core.css" rel="stylesheet" type="text/css" />
<table class="StudentPagingTablePanel">
<tr>
<td> 單位:<asp:Label ID="lblClassName" runat="server" Text="Label"></asp:Label></td>
<td>級別:<asp:Label ID="lblClassLevel" runat="server" Text="Label"></asp:Label>級節點</td>
</tr>
<tr>
<td>該單位共有<asp:Label ID="lblStudentType" runat="server" Text="Label"></asp:Label>學員
<asp:Label ID="lblStudentCount" runat="server" Text="Label"></asp:Label>人</td>
<td>每頁顯示<asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlPageSize_SelectedIndexChanged">
</asp:DropDownList>人 共<asp:Label ID="lblPageCount" runat="server" Text="Label"></asp:Label>頁
現為第<asp:Label ID="lblPageIndex" runat="server" Text="Label"></asp:Label>頁
<asp:LinkButton ID="firstPage" runat="server" CommandArgument="first"
oncommand="LinkButton_Command">首頁</asp:LinkButton>
<asp:LinkButton ID="nextPage" runat="server" CommandArgument="next"
oncommand="LinkButton_Command">下一頁</asp:LinkButton>
<asp:LinkButton ID="prevPage" runat="server" CommandArgument="prev"
oncommand="LinkButton_Command">上一頁</asp:LinkButton>
<asp:LinkButton ID="lastPage" runat="server" CommandArgument="last"
oncommand="LinkButton_Command">末頁</asp:LinkButton>
</td>
</tr>
</table>
<br />
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False"
EmptyDataText="沒有符合條件的數據">
<Columns>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:Image ID="Image1" CssClass="studentImage" ImageUrl =<%# GetStudentImageUrl(Eval("zpadress")) %> runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="姓名(中英簡)">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("xmjz") %>'></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text='<%# Eval("xmjy") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="jx" HeaderText="軍銜" />
<asp:BoundField DataField="zw" HeaderText="職務" />
<asp:BoundField DataField="gj" HeaderText="國家" />
<asp:BoundField DataField="sjyqk" HeaderText="文化程度" />
<asp:BoundField DataField="zj" HeaderText="宗教" />
<asp:TemplateField HeaderText="出生/入伍">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# SetBirthDate(Eval("csrq")) %>'></asp:Label>
<br />
<asp:Label ID="Label4" runat="server" Text='<%# SetEnrollDate(Eval("rwrq")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="xzz" HeaderText="房間/樓號" />
<asp:TemplateField HeaderText="電話/小號">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("dhd") %>'></asp:Label>
<br />
<asp:Label ID="Label6" runat="server" Text='<%# Eval("dhx") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fcjp" HeaderText="返程機票" />
<asp:BoundField DataField="xh" HeaderText="學號" />
</Columns>
</asp:GridView>
示例代碼,後台代碼
復制代碼 代碼如下:
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;
}
/// <summary>
/// 獲取QueryString傳遞參數
/// </summary>
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
///// <summary>
///// 獲取學員數據
///// </summary>
///// <param name="strSelect">顯示的字段</param>
///// <param name="strFrom">用到的</param>
/////<param name="strWhere">查詢條件</param>
///// <param name="pageSize">每頁顯示條數</param>
///// <param name="pageIndex">當前頁</param>
///// <returns></returns>
//protected DataTable GetStudentData(string strSelect,string strFrom,string strWhere,int pageSize,int pageIndex)
//{
// _command = _db.GetStoredProcCommand("StudentPaging");
// _db.AddInParameter(_command, "StrSelect", DbType.String, "zpadress,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,hzh,xh");
// _db.AddInParameter(_command, "StrFrom", DbType.String, "tx_xyzl");
// _db.AddInParameter(_command, "StrWhere", DbType.String, strWhere );
// _db.AddInParameter(_command, "StrOrder", DbType.String, "id");
// _db.AddInParameter(_command, "PageSize", DbType.Int32, pageSize );
// _db.AddInParameter(_command, "PageIndex", DbType.Int32,pageIndex );
// _studentTable = _db.ExecuteDataSet(_command).Tables[0];
// return _studentTable;
//}
#endregion
protected string GetStudentImageUrl(object imageUrl)
{
string serverUrl = http://192.168.0.1/admin;
string imageurl = string.Empty;
if (!(imageUrl == null))
{
string temp = imageUrl.ToString().Trim();
if (!string.IsNullOrEmpty(temp))
{ imageurl = string.Format("{0}{1}", serverUrl, temp.Substring(temp.IndexOf("/"))); }
}
return imageurl;
}
/// <summary>
/// 綁定分頁之後的數據
/// </summary>
/// <param name="pageSize">每頁顯示的數據量</param>
/// <param name="pageIndex">當前頁</param>
protected void BindStudentData(int pageSize, int pageIndex)
{
switch (_queryStringWhere)
{
case "jx":
this.gvStudent.DataSource = Helper.StudentPagingResult(
"zpadress,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,hzh,xh",
"student",
string.Format("dwbh='{0}' and jx='{1}'", _classCode, _studentType),
"id",
pageSize,
pageIndex);
this.gvStudent.DataBind();
break;
case "gj":
this.gvStudent.DataSource = Helper.StudentPagingResult(
"zpadress,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,hzh,xh",
"student",
string.Format("dwbh='{0}' and gj='{1}'", _classCode, _studentType),
"id",
pageSize,
pageIndex);
this.gvStudent.DataBind();
break;
case "allyear":
this.gvStudent.DataSource = Helper.StudentPagingResult(
"s.zpadress,s.xmjz,s.xmjy,s.jx,s.zw,s.gj,s.sjyqk,s.zj,s.csrq,s.rwrq,s.xzz,s.dhd,s.dhx,s.fcjp,s.hzh,s.xh",
"student as s inner join class as dw on s.dwbh=dw.bh",
string.Format(@"s.dwbh='{0}' and (dw.kxsj>=convert(datetime,'{1}'+'-01-01',120) and
dw.kxsj<=convert(datetime,'{1}'+'-12-31',120) or dw.bysj>=convert(datetime,'{1}'+'-01-01',120) and
dw.bysj<=convert(datetime,'{1}'+'-12-31',120)) ", _classCode, _studentType),
"s.id",
pageSize,
pageIndex);
this.gvStudent.DataBind();
break;
case "new":
this.gvStudent.DataSource = Helper.StudentPagingResult(
"s.zpadress,s.xmjz,s.xmjy,s.jx,s.zw,s.gj,s.sjyqk,s.zj,s.csrq,s.rwrq,s.xzz,s.dhd,s.dhx,s.fcjp,s.hzh,s.xh",
"student as s inner join class as dw on s.dwbh=dw.bh",
string.Format(@"s.dwbh='{0}' and (dw.kxsj>=convert(datetime,'{1}'+'-01-01',120) and
dw.kxsj<=convert(datetime,'{1}'+'-12-31',120)) ", _classCode, _studentType),
"s.id",
pageSize,
pageIndex);
this.gvStudent.DataBind();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (UserAuthHelper.GetUserAuthType("1") == UserAuthEnum.Admin||
UserAuthHelper.GetUserAuthType("2") == UserAuthEnum.CurrentStudentDetails)
{
GetQueryStringPara();
SetLabelText();
if (GetStudentCount() == 0)
{
StudentCountZero();
return;
}
if (!IsPostBack)
{
Filldata_dllPageSize();
SetPageIndex(1);
SetPageCount();
BindStudentData(GetPageSize(), GetPageIndex());
}
else
{
}
}
else
{
this.Controls.Add(new LiteralControl("您沒有相應的權限,請聯系管理員"));
}
}
/// <summary>
/// 獲取班級信息,班級全稱,班級級別
/// </summary>
/// <param name="classCode">班級編號</param>
/// <returns></returns>
protected ClassEntity GetClassInfo(string classCode)
{
ClassEntity entity = new ClassEntity();
entity.Code = classCode;
_command = _db.GetStoredProcCommand("ClassInfo");
_db.AddInParameter(_command, "bh", DbType.String, 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: <jiangrod>
-- Create date: <2010-03-03>
-- Description: <SQL2005及後續版本通用分頁存儲過程>調用方法: sp_Pager2005 'xtest','*','ORDER BY ID ASC','xname like ''%222name%''',2,20,0,0
-- 適合從單個表查詢數據
-- =============================================
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: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: 分頁獲取商品信息
--調用方法: Proc_GetProductPaged '2','*','','xname like ''%222name%''','ORDER BY ID ASC',20,2,0,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 ,N'@num INT output',@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