一、通用分页存储过程
首先创建一个通用的存储过程
ALTER PROCEDURE [dbo].[ProcDataPaging]
(
@tblName nvarchar(200), ----要显示的表或多个表的连接
@fieldKey nvarchar(150), ----主表的主键
@fieldNameShow nvarchar(500) = '*', ----要显示的字段列表
@pageSize int = 1, ----每页显示的记录个数
@pageCurrentSize int = 10, ----要显示那一页的记录
@fieldOrder nvarchar(200) = null, ----排序字段列表或条件
@Order bit = 0, ----排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')
@fieldWhere nvarchar(1000) = null, ----查询条件,不需where,以And开始
@fieldDistinct bit = 0 , ----是否添加查询字段的 DISTINCT 默认0不添加/1添加
@pageCount int = 1 output, ----查询结果分页后的总页数
@Counts int = 1 output, ----查询到的记录数
@strSql nvarchar(1000) = '' output -----最后返回的SQL语句
)
AS
SET NOCOUNT ON
Declare @sqlTmp nvarchar(1000) ----存放动态生成的SQL语句
Declare @strTmp nvarchar(1000) ----存放取得查询结果总数的查询语句
Declare @strID nvarchar(1000) ----存放取得查询开头或结尾fieldKey的查询语句
Declare @strSortType nvarchar(10) ----数据排序规则A
Declare @strFSortType nvarchar(10) ----数据排序规则B
Declare @SqlSelect nvarchar(50) ----对含有DISTINCT的查询进行SQL构造
Declare @SqlCounts nvarchar(50) ----对含有DISTINCT的总数查询进行SQL构造
if @fieldDistinct = 0
begin
set @SqlSelect = 'select '
set @SqlCounts = 'Count(*)'
end
else
begin
set @SqlSelect = 'select distinct '
set @SqlCounts = 'Count(DISTINCT '+@fieldKey+')'
end
if @Order=0
begin
set @strFSortType=' ASC '
set @strSortType=' DESC '
end
else
begin
set @strFSortType=' DESC '
set @strSortType=' ASC '
end
--------生成查询语句--------
--此处@strTmp为取得查询结果数量的语句
if @fieldWhere is null or @fieldWhere='' --没有设置显示条件
begin
set @sqlTmp = @fieldNameShow + ' From ' + @tblName
set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName
set @strID = ' From ' + @tblName
end
else
begin
set @sqlTmp = + @fieldNameShow + 'From ' + @tblName + ' where (1>0) ' + @fieldWhere
set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName + ' where (1>0) ' + @fieldWhere
set @strID = ' From ' + @tblName + ' where (1>0) ' + @fieldWhere
end
----取得查询结果总数量-----
exec sp_executesql @strTmp,N'@Counts int out ',@Counts out
declare @tmpCounts int
if @Counts = 0
set @tmpCounts = 1
else
set @tmpCounts = @Counts
--取得分页总数
set @pageCount=(@tmpCounts+@pageSize-1)/@pageSize
/**//**当前页大于总页数 取最后一页**/
if @pageCurrentSize>@pageCount
set @pageCurrentSize=@pageCount
--/*-----数据分页2分处理-------*/
declare @pageIndex int --总数/页大小
declare @lastcount int --总数%页大小
set @pageIndex = @tmpCounts/@pageSize
set @lastcount = @tmpCounts%@pageSize
if @lastcount > 0
set @pageIndex = @pageIndex + 1
else
set @lastcount = @pagesize
--//***显示分页
if @fieldWhere is null or @fieldWhere='' --没有设置显示条件
begin
set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fieldNameShow+' from '+@tblName
+' where '+@fieldKey+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@pageCurrentSize-1) as Varchar(20)) +' '+ @fieldKey +' from '+@tblName
+' order by '+ @fieldOrder +' '+ @strFSortType+')'
+' order by '+ @fieldOrder +' '+ @strFSortType
end
else --有查询条件
begin
set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fieldNameShow +' from '+@tblName
+' where '+@fieldKey+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@pageCurrentSize-1) as Varchar(20)) +' '+ @fieldKey +' from '+@tblName
+' Where (1>0) ' + @fieldWhere + ' order by '+ @fieldOrder +' '+ @strFSortType+')'
+' ' + @fieldWhere + ' order by '+ @fieldOrder +' '+ @strFSortType
end
------返回查询结果-----
set @strSql = @strTmp
exec sp_executesql @strTmp
--print @strTmp
二、asp.net利用aspnetpager组件实现分页的html
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="TopicID" ForeColor="#333333">
<Columns>
<asp:BoundField DataField="TopicID" HeaderText="编号" />
<asp:BoundField DataField="TopicTitle" HeaderText="管理员名称" />
<asp:BoundField DataField="UserName" HeaderText="真实姓名" />
<asp:BoundField DataField="CreatedOn" HeaderText="邮箱" />
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CommandName="del" OnClientClick="return window.confirm('确实要删除吗?');">删除</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<webdiyer:AspNetPager ID="AspNetPager1" runat="server" Width="100%" NumericButtonCount="6" UrlPaging="true"
NumericButtonTextFormatString="[{0}]" CustomInfoHTML="第 <font color='red'><b> %CurrentPageIndex% </b></font> 页 共 %PageCount% 页 显示 %StartRecordIndex%-%EndRecordIndex% 条" ShowCustomInfoSection="left"
FirstPageText="首页" LastPageText="末页" NextPageText="下页" PrevPageText="上页" Font-Names="Arial" BackColor="#F8B500" AlwaysShow="true" ShowInputBox="Always" SubmitButtonText="跳转" SubmitButtonStyle="botton"
OnPageChanged="AspNetPager1_PageChanged" OnPageChanging="AspNetPager1_PageChanging">
</webdiyer:AspNetPager>
三、详细code
protected void Page_Load(object sender, EventArgs e)
{
pi.BindDataForControl(GridView1, AspNetPager1);
}
protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
{
this.AspNetPager1.CurrentPageIndex = e.NewPageIndex;
pi.BindDataForControl(GridView1, AspNetPager1);
}
public static string connectionString = @"Server=LZF"LZF;Trusted_Connection=yes;database=FrogDB";
private string procName = "ProcDataPaging";//存储过程名字
private string tblName = "Topic"; //表名
private string fieldKey = "TopicID"; //主键字段
private string fieldNameShow = null; //显示需要字段
public int PageSize = 10; //每页显示的记录数
private int pageIndex = 1; //当前页的页码
private string fieldOrder = "TopicTitle"; //以逗号分隔的排序字段列表,可以指定在字段后面指定CreatedOn DESC/UserName ASC,用于指定排序顺序 --程序传参如:' SortA Asc,SortB Desc,SortC '
private bool Order = true; //排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记,且由Order来排序))
private string fieldWhere = ""; //查询条件,不需where,以And开始
private bool fieldDistinct = false; //是否添加查询字段的 DISTINCT 默认0不添加/1添加
public int PageCount; //查询结果分页后的总页数
public int Counts; //查询到的记录数
private string OutSelectSql; //最后返回的SQL语句
public void BindDataForControl(GridView gridView, AspNetPager aspnetPager)
{
pageIndex = aspnetPager.CurrentPageIndex;
if (pageIndex <= 0) pageIndex = 1;
DataSet ds = ReturnPageList(procName, tblName, fieldKey, fieldNameShow, PageSize, pageIndex, fieldOrder, Order, fieldWhere, fieldDistinct, out PageCount, out Counts, out OutSelectSql);
gridView.DataSource = ds.Tables[0];
gridView.DataBind();
aspnetPager.PageSize = 10;
aspnetPager.RecordCount = Counts;
}
/// <summary>
/// 分页存储过程 返回DataSet数据集
/// </summary>
/// <param name="procName"></param>
/// <param name="tblName">表名</param>
/// <param name="fieldKey">主键字段名</param>
/// <param name="fieldNameShow">显示需要字段</param>
/// <param name="pageSize">每页显示的记录数</param>
/// <param name="pageIndex">当前页的页码</param>
/// <param name="fieldOrder">以逗号分隔的排序字段列表,可以指定在字段后面指定CreatedOn DESC/UserName ASC,用于指定排序顺序 --程序传参如:' SortA Asc,SortB Desc,SortC '</param>
/// <param name="Order">排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记,且由Order来排序))</param>
/// <param name="fieldWhere">查询条件,不需where,以And开始</param>
/// <param name="Distinct">是否添加查询字段的 DISTINCT 默认0不添加/1添加</param>
/// <param name="pageCount">查询结果分页后的总页数</param>
/// <param name="Counts">查询到的记录数</param>
/// <param name="strSql">最后返回的SQL语句</param>
/// <returns>返回DataSet数据集</returns>
public static DataSet ReturnPageList(string procName, string tblName, string fieldKey, string fieldNameShow, int pageSize, int pageIndex,
string fieldOrder, bool Order, string fieldWhere, bool Distinct, out int pageCount, out int Counts, out string strSql)
{
SqlParameter[] commandParameters = new SqlParameter[]
{
new SqlParameter("@tblName", SqlDbType.NVarChar),
new SqlParameter("@fieldKey", SqlDbType.NVarChar),
new SqlParameter("@fieldNameShow", SqlDbType.NVarChar),
new SqlParameter("@pageSize", SqlDbType.Int),
new SqlParameter("@pageCurrentSize", SqlDbType.Int),
new SqlParameter("@fieldOrder", SqlDbType.NVarChar),
new SqlParameter("@Order", SqlDbType.Bit),
new SqlParameter("@fieldWhere", SqlDbType.NVarChar,1000),
new SqlParameter("@fieldDistinct", SqlDbType.Bit),
new SqlParameter("@pageCount", SqlDbType.Int,4),
new SqlParameter("@Counts", SqlDbType.Int,4),
new SqlParameter("@strSql", SqlDbType.NVarChar,1000)
};
commandParameters[0].Value = tblName;
commandParameters[1].Value = fieldKey;
commandParameters[2].Value = (fieldNameShow == null) ? "*" : fieldNameShow;
commandParameters[3].Value = (pageSize == 0) ? 10 : pageSize;
commandParameters[4].Value = pageIndex;
commandParameters[5].Value = fieldOrder;
commandParameters[6].Value = Order;
commandParameters[7].Value = (fieldWhere == null) ? "" : fieldWhere;
commandParameters[8].Value = Distinct;
commandParameters[9].Direction = ParameterDirection.Output;
commandParameters[10].Direction = ParameterDirection.Output;
commandParameters[11].Direction = ParameterDirection.Output;
DataSet set1 = RunProcedure(procName, commandParameters, tblName);
pageCount = (int)commandParameters[9].Value;
Counts = (int)commandParameters[10].Value;
strSql = commandParameters[11].Value.ToString();
return set1;
}
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
// 检查未分配值的输出参数,将其分配以DBNull.Value.
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
1、创建存储过程
create or replace package p_page is
type type_cur is ref cursor;
procedure ASPNETPAGE
(
TABLES VARCHAR2,
PK VARCHAR2,
SORT in out VARCHAR2,
PAGENUMBER in out NUMBER,
PAGESIZE NUMBER,
FIELDS VARCHAR2:='*',
FILTER VARCHAR2 :=null,
--GROUPS VARCHAR2 :=null,
ISCOUNT NUMBER :=0,
v_cur OUT type_cur
);
end p_page;
create OR REPLACE package body p_page is
procedure ASPNETPAGE
(
TABLES VARCHAR2,
PK VARCHAR2,
SORT in out VARCHAR2,
PAGENUMBER in out NUMBER,
PAGESIZE NUMBER,
FIELDS VARCHAR2:='*',
FILTER VARCHAR2 :=null,
--GROUPS VARCHAR2 :=null,
ISCOUNT NUMBER :=0 ,
v_cur OUT type_cur
)
as
STRFILTER VARCHAR2(1000);
STRSQL VARCHAR2(1000);
STARTID NUMBER;
ENDID NUMBER;
begin
--
--select * from GL_NEWS order by GN_UPDATE_DATE DESC
--exec Pg_Paging @Tables = 'tb_NewsInfo', @PK = 'News_ID', @Sort = 'News_ID DESC', @PageNumber = 2, @PageSize = 15,@Fields = '*', @Group = '', @isCount = 0
-- TABLES:=TRIM(TABLES);
-- FIELDS:=TRIM(FIELDS);
IF FILTER IS NOT NULL
THEN
STRFILTER := ' WHERE ' || FILTER || '';
ELSE
STRFILTER := '';
END IF;
IF (ISCOUNT = 1) THEN
STRSQL := 'SELECT COUNT(*) FROM ' || TABLES ||' '|| STRFILTER; --?眔????
ELSE -- 琌?????
IF (SORT IS NULL) THEN
SORT := PK || 'DESC';
END IF;
IF PAGENUMBER < 1 THEN PAGENUMBER := 1;
END IF;
IF PAGENUMBER =1 THEN --材?矗蔼┦
STRSQL := 'SELECT * FROM (SELECT ' || FIELDS || ' FROM ' || TABLES || ' ' || STRFILTER || ' ORDER BY ' || SORT ||') WHERE ROWNUM <= '||PAGESIZE ;
ELSE
STARTID := TO_CHAR((PAGENUMBER-1)*PAGESIZE + 1);
ENDID := TO_CHAR(PAGENUMBER*PAGESIZE);
IF FIELDS = '*' THEN
STRSQL := 'SELECT * FROM (SELECT '||TABLES||'.*,ROWNUM ROWN FROM (SELECT * FROM '||TABLES||' ' || STRFILTER || ' ORDER BY '||SORT|| ')'|| TABLES||' WHERE ROWNUM <= '|| ENDID||') D
WHERE ROWN >= '|| STARTID ;
ELSE
STRSQL := 'SELECT ' ||FIELDS || ' FROM (SELECT ' ||FIELDS || ',ROWNUM ROWN FROM (SELECT * FROM '|| TABLES||' ' || STRFILTER || ' ORDER BY '||SORT|| ')'|| TABLES||' WHERE ROWNUM <= '|| ENDID||') D
WHERE ROWN >= '|| STARTID ;
END IF;
END IF;
END IF;
--EXECUTE IMMEDIATE STRSQL;
OPEN v_cur FOR STRSQL;
end ASPNETPAGE;
end p_page;
2、在aspx页面中代码:
<webdiyer:AspNetPager ID="AspNetPager1" runat="server"
AlwaysShow="True"
CustomInfoHTML="第%CurrentPageIndex%页,共%PageCount%页,每页%PageSize%条"
FirstPageText="首页" LastPageText="尾页" NextPageText="下一页"
onpagechanged="AspNetPager1_PageChanged" PrevPageText="上一页"
ShowCustomInfoSection="Left" PageIndexBoxType="DropDownList"
ShowPageIndexBox="Always" SubmitButtonText="Go" TextAfterPageIndexBox="页" CenterCurrentPageButton="True"
TextBeforePageIndexBox="转到">
</webdiyer:AspNetPager>
3、后台:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;
using Ceshi.DataBase;
namespace Ceshi.COMM
{
public class AspNetPager
{
/// <summary>
/// 分页控件数据绑定
/// </summary>
/// <param name="tablename">表名称</param>
/// <param name="Pk">主键字段</param>
/// <param name="FIELDS">查询的字段 以逗号隔开</param>
/// <param name="FILTER">查询条件 没有条件1=1 不要where</param>
/// <param name="SORT">排序 id desc</param>
/// <param name="AspNetPager1">分页控件</param>
/// <param name="GridView1">GridView控件</param>
public static void DataBind(string tablename, string Pk, string FIELDS, string FILTER, string SORT, Wuqi.Webdiyer.AspNetPager AspNetPager1, System.Web.UI.WebControls.GridView GridView1)
{
try
{
int pageindex = 0;
//string t_find = "1";
//string strWhere = " id like '" + t_find + "%'";
if (AspNetPager1.CurrentPageIndex < 1)
{
pageindex = 1;
}
else
{
pageindex = AspNetPager1.CurrentPageIndex;
}
OracleParameter[] parameters ={
new OracleParameter("TABLES",OracleType.VarChar,255),
new OracleParameter("PK",OracleType.VarChar,1000),
new OracleParameter("SORT",OracleType.VarChar,255),
new OracleParameter("PAGENUMBER",OracleType.Number),
new OracleParameter("PAGESIZE",OracleType.Number),
new OracleParameter("FILTER",OracleType.VarChar,2000),
new OracleParameter("FIELDS",OracleType.VarChar,255),
new OracleParameter("v_cur",OracleType.cur.Cursor),
new OracleParameter("ISCOUNT",OracleType.Number)};
parameters[0].Value = tablename;// "test";
parameters[1].Value = Pk;//主键
parameters[2].Value = SORT;// "id desc";//排序
parameters[3].Value = pageindex;//索引页
parameters[4].Value = AspNetPager1.PageSize;//多少条为一页
parameters[5].Value = FILTER;// strWhere;//查询条件组合
parameters[6].Value = FIELDS;// "id,name";//查询的字段
parameters[7].Direction = ParameterDirection.Output;//输出
parameters[8].Value = 0;
DataSet ds2 = OracleHelper.GetDataset(CommandType.StoredProcedure, "p_page.ASPNETPAGE", parameters);
parameters[parameters.Length - 1].Value = 1;
AspNetPager1.RecordCount = OracleHelper.ExecuteReader(CommandType.StoredProcedure, "p_page.ASPNETPAGE", parameters);
GridView1.DataSource = ds2.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Ceshi.COMM.Logger.Info(ex.Message);
}
}
/// <summary>
/// 分页控件数据绑定 datalist
/// </summary>
/// <param name="tablename">表名称</param>
/// <param name="Pk">主键字段</param>
/// <param name="FIELDS">查询的字段 以逗号隔开</param>
/// <param name="FILTER">查询条件 没有条件1=1 不要where</param>
/// <param name="SORT">排序 id desc</param>
/// <param name="AspNetPager1">分页控件</param>
/// <param name="GridView1">datalist控件</param>
public static void DataBindDataList(string tablename, string Pk, string FIELDS, string FILTER, string SORT, Wuqi.Webdiyer.AspNetPager AspNetPager1, System.Web.UI.WebControls.DataList DataList1)
{
try
{
int pageindex = 0;
//string t_find = "1";
//string strWhere = " id like '" + t_find + "%'";
if (AspNetPager1.CurrentPageIndex < 1)
{
pageindex = 1;
}
else
{
pageindex = AspNetPager1.CurrentPageIndex;
}
OracleParameter[] parameters ={
new OracleParameter("TABLES",OracleType.VarChar,255),
new OracleParameter("PK",OracleType.VarChar,1000),
new OracleParameter("SORT",OracleType.VarChar,255),
new OracleParameter("PAGENUMBER",OracleType.Number),
new OracleParameter("PAGESIZE",OracleType.Number),
new OracleParameter("FILTER",OracleType.VarChar,2000),
new OracleParameter("FIELDS",OracleType.VarChar,255),
new OracleParameter("v_cur",OracleType.Cursor),
new OracleParameter("ISCOUNT",OracleType.Number)};
parameters[0].Value = tablename;// "test";
parameters[1].Value = Pk;//主键
parameters[2].Value = SORT;// "id desc";//排序
parameters[3].Value = pageindex;//索引页
parameters[4].Value = AspNetPager1.PageSize;//多少条为一页
parameters[5].Value = FILTER;// strWhere;//查询条件组合
parameters[6].Value = FIELDS;// "id,name";//查询的字段
parameters[7].Direction = ParameterDirection.Output;//输出
parameters[8].Value = 0;
DataSet ds2 = OracleHelper.GetDataset(CommandType.StoredProcedure, "p_page.ASPNETPAGE", parameters);
parameters[parameters.Length - 1].Value = 1;
AspNetPager1.RecordCount = OracleHelper.ExecuteReader(CommandType.StoredProcedure, "p_page.ASPNETPAGE", parameters);
DataList1.DataSource = ds2.Tables[0].DefaultView;
DataList1.DataBind();
}
catch (Exception ex)
{
Ceshi.COMM.Logger.Info(ex.Message);
}
}
public static DataSet aa(int id)
{
Ceshi.DataBase.OracleHelper DbHelperSQL = new OracleHelper();
OracleParameter[] parameters =
{
new OracleParameter("v_cur",OracleType.Cursor),
new OracleParameter("PR_HACODE",OracleType.Number)
};
parameters[0].Direction = ParameterDirection.Output;
parameters[1].Value = id;
return DbHelperSQL.RunProcedure("P_HAAUDIT.HTTOCUSTADUITCURR", parameters, "table0");
}
}
}