分頁存儲過程html
- USE [MyTest]
- GO
- /****** Object: StoredProcedure [dbo].[PageTable] Script Date: 03/02/2012 15:11:29 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- --- 分頁的存儲過程
- Create procedure [dbo].[PageTable]
- @tableName varchar(200), ---表名
- @fieldList varchar(2000),---顯示列名
- @primaryKey varchar(100),---單一主鍵或惟一值鍵
- @where varchar(5000),---查詢條件 不含‘where’字符
- @order varchar(1000),---排序 不含‘order by’ 如id desc ,userid asc 當@sortType=3時生效
- @sortType int,---排序規則 1.正序 asc 2. 倒序 desc 3.多列排序
- @recorderCount int,---記錄總數,會返回總記錄數
- @PageSize int,---每頁輸出的記錄數
- @PageIndex int,---當前頁數
- @totalCount int output,---返回記錄總數
- @totalPageCount int output---返回總頁數
- as
- begin
- if ISNULL(@tableName,'')='' OR ISNULL(@fieldList,'')='' ----確保主要的幾個輸入參數有效
- OR ISNULL (@primaryKey,'')=''
- OR @sortType<1 OR @sortType>3
- OR @recorderCount<0 OR @PageSize<0 OR @PageIndex<0
- begin
- return
- end
- declare @new_where1 varchar(3000)
- declare @new_where2 varchar(3000)
- declare @new_order varchar(1000)
- declare @sql varchar(8000)
- declare @sqlCount nvarchar(4000) --- SP_EXECUTESQl 第一個參數必須是"ntext/nchar/nvarchar"類型
- if ISNULL (@where ,'')='' --@where 爲null 的話替換成 ‘’,而後判斷 @where=''?
- begin
- set @new_where1=''
- set @new_where2=' where '
- end
- else --若@where 不爲空 ,設置@new_where1 和@new_where2 ,包含‘where’字符
- begin
- set @new_where1=' where '+@where
- set @new_where2=' where '+@where +' and '
- end
- if ISNULL(@order ,'')='' OR @sortType=1 OR @sortType=2 --簡單排序
- begin
- if @sortType=1 set @new_order=' order by '+@primaryKey+' asc '
- if @sortType=2 set @new_order =' order by '+@primaryKey+' desc '
- end
- else --多列排序 @sortType=3 && @order<>''
- begin
- set @new_order=' order by '+@order
- end
- --ceiling (29.0)取出大於或等於29.0的最小整數 29
- --ceiling (29.1)取出大於或等於29.0的最小整數 30
- --CEILING(COUNT(*)+0.0)/CAST(4 as varchar) as TotalPageCount
- set @sqlCount='select @totalCount=count(*), @totalPageCount=ceiling((count(*)+0.0)/'+CAST(@PageSize as varchar)
- +') from '+@tableName +''+@new_where1
- --設置 @totalCount @totalPageCount 的值 ,總頁數=總記錄數/每頁記錄數(恰爲整數) 總頁數=總記錄數/每頁記錄數+1(最後不是整頁)
- if @recorderCount=0
- begin
- ---SP_EXECUTESQl 執行動態sql :@sqlCount是動態sql的定義,
- --N'@totalCount int output,@totalPageCount int output'是 對動態sql中變量的聲明
- --@totalCount output,@totalPageCount output 是對變量的賦值
- exec SP_EXECUTESQl @sqlCount,N'@totalCount int output ,@totalPageCount int output',@totalCount output,@totalPageCount output
- end
- else
- begin
- select @recorderCount=@totalCount
- end
- if @PageIndex>CEILING((@totalCount+0.0)/@PageSize)
- begin
- set @PageIndex=CEILING((@totalCount+0.0)/@pageSize)--將超出最大範圍的頁 設置爲最後一頁
- end
- if @PageIndex=0
- begin
- set @PageIndex=1 --將超出最小範圍的頁 設置爲第一頁
- end
- if @PageIndex=1 --選擇第一頁的數據
- begin
- set @sql ='select top '+STR(@PageSize)+''+@fieldList+' from '+@tableName+''+@new_where1+''+@new_order
- end
- else --其餘頁時
- begin
- if @sortType=1 --普通升序 primary key asc
- begin
- set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_where2+'' +@primaryKey+'>'
- +'(select MAX('+@primaryKey+') from (select top '+STR(@pageSize *(@PageIndex-1))+''+@primaryKey+' from '
- +@tableName+''+@new_where1+''+@new_order+') as TMP)'+@new_order
- end
- if @sortType=2 --普通降序 primary key desc
- begin
- --if @PageIndex=1
- --begin
- --set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_order
- --end
- --else
- --begin
- set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_where2 +''+@primaryKey+'<'
- +'(select MIN('+@primaryKey+') from (select top '+STR(@pageSize *(@PageIndex-1))+''+@primaryKey+' from '
- +@tableName+''+@new_where1+''+@new_order+') as TMP)'+@new_order
- --end
- end
- if @sortType=3 ---多列排序
- begin
- set @sql='select top'+STR(@PageSize)+''+@fieldList+' from '+@tableName+''+@new_where2+''+@primaryKey
- +' not in(select top '+STR(@PageSize*(@pageIndex-1))+''+@primaryKey+' from '+@tableName+''+@new_where1
- +''+@new_order+')'+@new_order
- end
- end
- exec (@sql)
- end
- --測試 例子
- --declare @totalCount int
- --declare @totalPageCount int
- --exec dbo.PageTable 'Category','id,name,class, grade','id','grade>=60','grade desc ,name asc',3,12,6,1,@totalCount ,@totalPageCount
aspx頁面sql
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewDetail.aspx.cs" Inherits="ViewDetail" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <%=tableString %> <%--獲取後天拼接的 html--%> <%-- 獲取後臺變量值--%>
- 當前頁碼:<asp:Label ID ="lblPage" runat="server" ><%=Session["pageIndex"]%></asp:Label>
- 總頁碼:<asp:Label ID ="lblTag" runat="server"><%=totalPageCount %></asp:Label>
- 總條數:<asp:Label ID ="Label1" runat="server"><%=totalCount %></asp:Label>
- <%-- 測試:<asp:Label ID ="Label1" runat="server" ><%=test %></asp:Label>--%> <%-- 服務器端控件 (取後臺變量的值)--%>
- <%-- 測試2 :<input id="Text2" type="text" value='<%=test %>' />--%> <%-- 客戶端控件 (取後臺變量的值)--%>
- <br />
- <asp:LinkButton ID="lbtnFirst" runat="server" onclick="lbtnFirst_Click">第一頁</asp:LinkButton>
- <asp:LinkButton ID="lbtnPre" runat="server" onclick="lbtnPre_Click">上一頁</asp:LinkButton>
- <asp:LinkButton ID="lbtnNext" runat="server" onclick="lbtnNext_Click">下一頁</asp:LinkButton>
- <asp:LinkButton ID="lbtnLast" runat="server" onclick="lbtnLast_Click">最後一頁</asp:LinkButton>
- <%--本例中僅用到 <%=變量名%> ,如下是與本例無關的幾種類似結構 <% # 字段名%> <% %>--%>
- <%-- 1. <% %> :內聯代碼塊,能夠在 *.aspx 或 *.ascx 文件裏嵌入後臺代碼 --%>
- <%-- <%
- for (int i = 0; i < 20; i++)
- {
- Response.Write(i);
- }
- %> --%>
- <%-- 2. <% @ %> 是在 *.aspx頁面前臺代碼導入命名空間 ,像本文第一行--%>>
- <%-- < %@ Import namespace="System.Data"%>--%>
- <%-- 3. < %#... %>: 是在綁定控件DataBind()方法執行時被執行,用於數據綁定,取綁定某字段值--%>
- <%-- <%#DataBinder.Eval(Container.DataItem,"name") %>--%>
- <%-- 4. < %= %>: 在程序執行時被調用,能夠顯示後臺變量值--%>
- <%--< %=name %> --%>
- <%-- 對應的 *.cs中: protected string name="姓名"; 其中訪問修飾符最低爲 protected,不然取不到值的--%>
- </div>
- </form>
- </body>
- </html>
C#後臺代碼服務器
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Text;
- public partial class ViewDetail : System.Web.UI.Page
- {
- private string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- public string name;
- public string classname;
- protected string tableString;
- public static int totalPageCount;
- public static int totalCount; //注意定義爲靜態 不然在連接事件(選擇頁面事件)中取不到值
- //public int test=100; // 與本例無關,用於區分aspx頁面服務器控件、 客戶端控件 取後臺值的不一樣 ,見aspx頁面中對應的註冊部分
- protected void Page_Load(object sender, EventArgs e)
- {
- //Response.Write("由頁面Default傳過來的記錄 ID 是 "+Request.QueryString["id"]) ;
- if (!IsPostBack)
- {
- Session["pageIndex"] = 1;//頁面初加載,顯示第一頁數據 ,Session["pageIndex"]保存當前顯示頁碼
- BindRepeater();
- }
- }
- private void BindRepeater()
- {
- //定義接收數據的表結構
- DataTable tb = new DataTable();
- tb.Columns.Add("id");
- tb.Columns.Add("name");
- tb.Columns.Add("class");
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.CommandType = CommandType.StoredProcedure;//指定是存儲過程
- cmd.CommandText = "PageTable";// 過程的名字
- #region 參數必須與存儲過程的參數一一對應
- //定義輸入參數
- cmd.Parameters.Add(new SqlParameter("@tableName", SqlDbType.VarChar)).Value = "Category"; //表名
- cmd.Parameters.Add(new SqlParameter("@fieldList", SqlDbType.VarChar)).Value = "id,name,class";// 獲取的字段
- cmd.Parameters.Add(new SqlParameter("@primaryKey", SqlDbType.VarChar)).Value = "id";//主鍵列
- cmd.Parameters.Add(new SqlParameter("@where", SqlDbType.VarChar)).Value = "grade>=60";//不包含where 關鍵字的條件
- cmd.Parameters.Add(new SqlParameter("@order", SqlDbType.VarChar)).Value = "grade desc ,name asc";//不包含order by 關鍵字的排序條件
- cmd.Parameters.Add(new SqlParameter("@sortType", SqlDbType.Int)).Value = 3; //1 正序 2 倒序 3 組合排序 ( 選爲 3 時, @order 纔有效)
- cmd.Parameters.Add(new SqlParameter("@recorderCount", SqlDbType.Int)).Value = 0;//記錄總數
- cmd.Parameters.Add(new SqlParameter("@PageSize", SqlDbType.Int)).Value = 6;//頁面大小(記錄數量)
- cmd.Parameters.Add(new SqlParameter("@PageIndex", SqlDbType.Int)).Value = Session["pageIndex"];//當前頁數
- //定義輸出參數
- SqlParameter sp = cmd.Parameters.Add(new SqlParameter("@totalCount", SqlDbType.Int)); // 總記錄數量
- sp.Direction = ParameterDirection.Output;
- SqlParameter sp2 = cmd.Parameters.Add(new SqlParameter("@totalPageCount", SqlDbType.Int));//總頁數
- sp2.Direction = ParameterDirection.Output;
- #endregion
- cmd.Connection = conn;
- SqlDataReader dr = cmd.ExecuteReader();
- #region 注意此處不要用if,不然只能讀出第一條數據
- //if (dr.Read()) // 注意此處不要用if,不然只能讀出第一條數據
- //{
- // tb.Rows.Add(dr["id"].ToString(), dr["name"].ToString(), dr["class"].ToString());
- //}
- #endregion
- while (dr.Read())
- {
- tb.Rows.Add(dr["id"], dr["name"].ToString(), dr["class"].ToString());//插入行數據
- }
- conn.Close();
- Object obj = cmd.Parameters["@totalPageCount"].Value;
- if (obj != DBNull.Value)
- totalPageCount = Convert.ToInt32(obj); //獲取輸出參數 (總頁數)
- Object oj = cmd.Parameters["@totalCount"].Value;
- totalCount = Convert.ToInt32(oj); //獲取輸出參數(總記錄條數)
- tableString= getHtmlTable(tb);// 將獲取的表數據格式化拼接
- }
- private string getHtmlTable(DataTable tb)
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("<table><tr><th>姓名</th><th>班級</th></tr>");
- foreach (DataRow dr in tb.Rows)
- {
- sb.Append("<tr><td>");
- sb.Append(dr["name"]);// 獲取某列數據 dr["列名"]
- sb.Append("</td><td>");
- sb.Append(dr["class"]);
- sb.Append("</td></tr>");
- }
- sb.Append("</table>");
- return sb.ToString();
- }
- protected void lbtnFirst_Click(object sender, EventArgs e)
- {
- Session["pageIndex"] = 1;
- BindRepeater();
- }
- protected void lbtnPre_Click(object sender, EventArgs e)
- {
- if (Convert.ToInt32(Session["pageIndex"]) > 1)
- Session["pageIndex"] = Convert.ToInt32(Session["pageIndex"]) - 1;
- else
- Session["pageIndex"] = 1; //當前已經是第一頁
- BindRepeater();
- }
- protected void lbtnNext_Click(object sender, EventArgs e)
- {
- if (Convert.ToInt32(Session["pageIndex"]) < totalPageCount)
- Session["pageIndex"] = Convert.ToInt32(Session["pageIndex"]) + 1;
- else
- Session["pageIndex"] = totalPageCount; //當前已經是最後一頁
- BindRepeater();
- }
- protected void lbtnLast_Click(object sender, EventArgs e)
- {
- Session["pageIndex"] = totalPageCount;
- BindRepeater();
- }
- }