存儲過程實現分頁(不使用控件)

分頁存儲過程html

  
  
  
  
  1. USE [MyTest]  
  2. GO  
  3. /****** Object:  StoredProcedure [dbo].[PageTable]    Script Date: 03/02/2012 15:11:29 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8.  
  9. --- 分頁的存儲過程  
  10. Create procedure [dbo].[PageTable]  
  11.  
  12. @tableName varchar(200), ---表名  
  13. @fieldList varchar(2000),---顯示列名  
  14. @primaryKey varchar(100),---單一主鍵或惟一值鍵  
  15. @where varchar(5000),---查詢條件 不含‘where’字符  
  16. @order varchar(1000),---排序 不含‘order by’ 如id desc ,userid asc  當@sortType=3時生效   
  17.  
  18. @sortType int,---排序規則 1.正序 asc 2. 倒序 desc 3.多列排序  
  19. @recorderCount int,---記錄總數,會返回總記錄數  
  20. @PageSize int,---每頁輸出的記錄數  
  21. @PageIndex int,---當前頁數  
  22. @totalCount int output,---返回記錄總數  
  23. @totalPageCount int output---返回總頁數  
  24.  
  25. as   
  26. begin  
  27.  
  28. if ISNULL(@tableName,'')='' OR ISNULL(@fieldList,'')=''  ----確保主要的幾個輸入參數有效  
  29.     OR ISNULL (@primaryKey,'')=''  
  30.     OR @sortType<1 OR @sortType>3  
  31.     OR @recorderCount<0 OR @PageSize<0 OR @PageIndex<0 
  32. begin   
  33.     return   
  34. end   
  35.  
  36. declare @new_where1 varchar(3000)  
  37. declare @new_where2 varchar(3000)  
  38. declare @new_order varchar(1000)  
  39. declare @sql varchar(8000)  
  40. declare @sqlCount nvarchar(4000) --- SP_EXECUTESQl 第一個參數必須是"ntext/nchar/nvarchar"類型  
  41.  
  42. if ISNULL (@where ,'')='' --@where 爲null 的話替換成 ‘’,而後判斷 @where=''?  
  43. begin   
  44.     set @new_where1='' 
  45.     set @new_where2=' where ' 
  46. end  
  47. else    --若@where 不爲空 ,設置@new_where1 和@new_where2 ,包含‘where’字符  
  48. begin  
  49.     set @new_where1=' where '+@where  
  50.     set @new_where2=' where '+@where +' and '  
  51. end   
  52.  
  53. if ISNULL(@order ,'')='' OR @sortType=1 OR @sortType=2  --簡單排序  
  54. begin   
  55.     if @sortType=1 set @new_order=' order by '+@primaryKey+' asc '  
  56.     if @sortType=2 set @new_order =' order by '+@primaryKey+' desc '  
  57. end  
  58. else --多列排序 @sortType=3 && @order<>''  
  59. begin  
  60.     set @new_order=' order by '+@order  
  61. end  
  62.         --ceiling (29.0)取出大於或等於29.0的最小整數 29  
  63.         --ceiling (29.1)取出大於或等於29.0的最小整數 30  
  64.         --CEILING(COUNT(*)+0.0)/CAST(4 as varchar) as TotalPageCount   
  65. set @sqlCount='select @totalCount=count(*), @totalPageCount=ceiling((count(*)+0.0)/'+CAST(@PageSize as varchar)  
  66.     +') from '+@tableName +''+@new_where1    
  67.     --設置 @totalCount @totalPageCount 的值 ,總頁數=總記錄數/每頁記錄數(恰爲整數) 總頁數=總記錄數/每頁記錄數+1(最後不是整頁)  
  68.  
  69. if @recorderCount=0 
  70. begin   
  71.     ---SP_EXECUTESQl 執行動態sql :@sqlCount是動態sql的定義,  
  72.     --N'@totalCount int output,@totalPageCount int output'是 對動態sql中變量的聲明  
  73.     --@totalCount output,@totalPageCount output 是對變量的賦值  
  74. exec SP_EXECUTESQl @sqlCount,N'@totalCount int output ,@totalPageCount int output',@totalCount output,@totalPageCount output  
  75.  
  76. end   
  77. else  
  78. begin   
  79.  
  80. select @recorderCount=@totalCount  
  81.  
  82. end  
  83.  
  84. if @PageIndex>CEILING((@totalCount+0.0)/@PageSize)   
  85. begin  
  86. set @PageIndex=CEILING((@totalCount+0.0)/@pageSize)--將超出最大範圍的頁 設置爲最後一頁  
  87. end  
  88. if @PageIndex=0 
  89. begin   
  90.     set @PageIndex=1 --將超出最小範圍的頁 設置爲第一頁  
  91. end   
  92. if @PageIndex=1 --選擇第一頁的數據  
  93. begin   
  94.     set @sql ='select top '+STR(@PageSize)+''+@fieldList+' from '+@tableName+''+@new_where1+''+@new_order  
  95. end   
  96. else --其餘頁時  
  97. begin   
  98. if @sortType=1  --普通升序 primary key asc  
  99. begin   
  100.  
  101.     set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_where2+'' +@primaryKey+'>'  
  102.     +'(select MAX('+@primaryKey+') from (select top '+STR(@pageSize *(@PageIndex-1))+''+@primaryKey+' from '  
  103.     +@tableName+''+@new_where1+''+@new_order+') as TMP)'+@new_order   
  104. end   
  105.  
  106. if @sortType=2 --普通降序 primary key desc  
  107. begin  
  108.  --if @PageIndex=1 
  109.  --begin  
  110.  --set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_order  
  111.  --end  
  112.  --else  
  113.  --begin  
  114.     set @sql='select top '+STR(@PageSize)+''+@fieldList +' from '+@tableName+''+@new_where2 +''+@primaryKey+'<'  
  115.     +'(select MIN('+@primaryKey+') from (select top '+STR(@pageSize *(@PageIndex-1))+''+@primaryKey+' from '  
  116.     +@tableName+''+@new_where1+''+@new_order+') as TMP)'+@new_order   
  117.  --end  
  118. end  
  119.  
  120. if @sortType=3  ---多列排序  
  121. begin  
  122.     set @sql='select top'+STR(@PageSize)+''+@fieldList+' from '+@tableName+''+@new_where2+''+@primaryKey   
  123.     +' not in(select top '+STR(@PageSize*(@pageIndex-1))+''+@primaryKey+' from '+@tableName+''+@new_where1  
  124.     +''+@new_order+')'+@new_order  
  125. end  
  126.  
  127. end  
  128.  
  129. exec (@sql)  
  130.  
  131. end  
  132.  
  133.  
  134.  
  135. --測試 例子  
  136. --declare @totalCount int  
  137. --declare @totalPageCount int  
  138. --exec dbo.PageTable 'Category','id,name,class, grade','id','grade>=60','grade desc ,name asc',3,12,6,1,@totalCount ,@totalPageCount 

 

aspx頁面sql

 

  
  
  
  
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewDetail.aspx.cs" Inherits="ViewDetail" %> 
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml"> 
  6. <head runat="server"> 
  7.     <title></title> 
  8. </head> 
  9. <body> 
  10.     <form id="form1" runat="server">    
  11.     <div>       
  12.      <%=tableString %> <%--獲取後天拼接的 html--%>     <%--  獲取後臺變量值--%> 
  13.       當前頁碼:<asp:Label ID ="lblPage" runat="server" ><%=Session["pageIndex"]%></asp:Label> &nbsp;&nbsp;&nbsp;  
  14.      
  15.       總頁碼:<asp:Label ID ="lblTag" runat="server"><%=totalPageCount %></asp:Label>&nbsp;&nbsp;&nbsp;  
  16.         
  17.       總條數:<asp:Label ID ="Label1" runat="server"><%=totalCount %></asp:Label> 
  18.     
  19.         
  20.      <%-- 測試:<asp:Label ID ="Label1" runat="server" ><%=test %></asp:Label>--%> <%-- 服務器端控件 (取後臺變量的值)--%> 
  21.      <%-- 測試2 :<input id="Text2" type="text" value='<%=test %>' />--%>  <%-- 客戶端控件 (取後臺變量的值)--%> 
  22.      <br /> 
  23.       <asp:LinkButton ID="lbtnFirst" runat="server" onclick="lbtnFirst_Click">第一頁</asp:LinkButton> 
  24.       <asp:LinkButton ID="lbtnPre" runat="server" onclick="lbtnPre_Click">上一頁</asp:LinkButton> 
  25.       <asp:LinkButton ID="lbtnNext" runat="server" onclick="lbtnNext_Click">下一頁</asp:LinkButton> 
  26.       <asp:LinkButton ID="lbtnLast" runat="server" onclick="lbtnLast_Click">最後一頁</asp:LinkButton> 
  27.         
  28.         
  29.         
  30.         
  31.       <%--本例中僅用到 <%=變量名%>  ,如下是與本例無關的幾種類似結構 <% # 字段名%>  <% %>--%> 
  32.         
  33.       <%--  1.  <% %> :內聯代碼塊,能夠在 *.aspx 或 *.ascx 文件裏嵌入後臺代碼  --%> 
  34.  <%--   <%  
  35.           for (int i = 0; i < 20; i++)  
  36.           {  
  37.               Response.Write(i);  
  38.           }  
  39.       %>    --%> 
  40.         
  41.       <%-- 2.  <% @  %> 是在 *.aspx頁面前臺代碼導入命名空間 ,像本文第一行--%>> 
  42.        <%-- < %@ Import namespace="System.Data"%>--%> 
  43.          
  44.       <%-- 3.  < %#... %>: 是在綁定控件DataBind()方法執行時被執行,用於數據綁定,取綁定某字段值--%> 
  45.        <%-- <%#DataBinder.Eval(Container.DataItem,"name") %>--%> 
  46.          
  47.       <%-- 4.   < %= %>: 在程序執行時被調用,能夠顯示後臺變量值--%> 
  48.         
  49.          <%--< %=name %> --%>     
  50.          <%-- 對應的 *.cs中: protected string name="姓名"; 其中訪問修飾符最低爲 protected,不然取不到值的--%> 
  51.         
  52.      </div> 
  53.     </form> 
  54. </body> 
  55. </html> 

C#後臺代碼服務器

 

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Text;  
  11.  
  12. public partial class ViewDetail : System.Web.UI.Page  
  13. {  
  14.     private string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  15.     public string name;  
  16.     public string classname;  
  17.     protected string tableString;  
  18.  
  19.     public static int totalPageCount;  
  20.     public static int totalCount; //注意定義爲靜態  不然在連接事件(選擇頁面事件)中取不到值  
  21.  
  22.       //public int test=100;  // 與本例無關,用於區分aspx頁面服務器控件、 客戶端控件 取後臺值的不一樣 ,見aspx頁面中對應的註冊部分  
  23.     
  24.     protected void Page_Load(object sender, EventArgs e)  
  25.     {  
  26.          
  27.         //Response.Write("由頁面Default傳過來的記錄 ID 是 "+Request.QueryString["id"]) ;  
  28.         if (!IsPostBack)  
  29.         {  
  30.             Session["pageIndex"] = 1;//頁面初加載,顯示第一頁數據 ,Session["pageIndex"]保存當前顯示頁碼  
  31.             BindRepeater();  
  32.         }     
  33.         
  34.     }  
  35.     private void BindRepeater()  
  36.     {   
  37.         //定義接收數據的表結構  
  38.         DataTable tb = new DataTable();  
  39.         tb.Columns.Add("id");  
  40.         tb.Columns.Add("name");  
  41.         tb.Columns.Add("class");  
  42.          
  43.               
  44.         SqlConnection conn = new SqlConnection(StrConn);  
  45.           
  46.         conn.Open();  
  47.         SqlCommand cmd = new SqlCommand();  
  48.         cmd.CommandType = CommandType.StoredProcedure;//指定是存儲過程  
  49.         cmd.CommandText = "PageTable";// 過程的名字  
  50.  
  51.         #region 參數必須與存儲過程的參數一一對應  
  52.         //定義輸入參數  
  53.         cmd.Parameters.Add(new SqlParameter("@tableName", SqlDbType.VarChar)).Value = "Category"; //表名  
  54.         cmd.Parameters.Add(new SqlParameter("@fieldList", SqlDbType.VarChar)).Value = "id,name,class";// 獲取的字段  
  55.         cmd.Parameters.Add(new SqlParameter("@primaryKey", SqlDbType.VarChar)).Value = "id";//主鍵列  
  56.         cmd.Parameters.Add(new SqlParameter("@where", SqlDbType.VarChar)).Value = "grade>=60";//不包含where 關鍵字的條件  
  57.         cmd.Parameters.Add(new SqlParameter("@order", SqlDbType.VarChar)).Value = "grade desc ,name asc";//不包含order by 關鍵字的排序條件  
  58.  
  59.         cmd.Parameters.Add(new SqlParameter("@sortType", SqlDbType.Int)).Value = 3; //1 正序 2 倒序 3 組合排序 ( 選爲 3 時, @order 纔有效)  
  60.         cmd.Parameters.Add(new SqlParameter("@recorderCount", SqlDbType.Int)).Value = 0;//記錄總數  
  61.         cmd.Parameters.Add(new SqlParameter("@PageSize", SqlDbType.Int)).Value = 6;//頁面大小(記錄數量)        
  62.         cmd.Parameters.Add(new SqlParameter("@PageIndex", SqlDbType.Int)).Value = Session["pageIndex"];//當前頁數  
  63.  
  64.         //定義輸出參數  
  65.         SqlParameter sp = cmd.Parameters.Add(new SqlParameter("@totalCount", SqlDbType.Int));  // 總記錄數量  
  66.         sp.Direction = ParameterDirection.Output;  
  67.         SqlParameter sp2 = cmd.Parameters.Add(new SqlParameter("@totalPageCount", SqlDbType.Int));//總頁數  
  68.         sp2.Direction = ParameterDirection.Output;  
  69.         #endregion  
  70.  
  71.         cmd.Connection = conn;  
  72.         SqlDataReader dr = cmd.ExecuteReader();  
  73.  
  74.         #region  注意此處不要用if,不然只能讀出第一條數據  
  75.         //if (dr.Read()) // 注意此處不要用if,不然只能讀出第一條數據  
  76.         //{  
  77.         //    tb.Rows.Add(dr["id"].ToString(), dr["name"].ToString(), dr["class"].ToString());  
  78.         //}  
  79.         #endregion  
  80.         while (dr.Read())  
  81.         {  
  82.             tb.Rows.Add(dr["id"], dr["name"].ToString(), dr["class"].ToString());//插入行數據  
  83.         }  
  84.         conn.Close();  
  85.        
  86.         Object obj = cmd.Parameters["@totalPageCount"].Value;  
  87.         if (obj != DBNull.Value)  
  88.             totalPageCount = Convert.ToInt32(obj); //獲取輸出參數 (總頁數)  
  89.         Object oj = cmd.Parameters["@totalCount"].Value;   
  90.              totalCount = Convert.ToInt32(oj); //獲取輸出參數(總記錄條數)  
  91.  
  92.       tableString=  getHtmlTable(tb);// 將獲取的表數據格式化拼接  
  93.     }  
  94.     private string getHtmlTable(DataTable tb)  
  95.     {  
  96.         StringBuilder sb = new StringBuilder();  
  97.         sb.Append("<table><tr><th>姓名</th><th>班級</th></tr>");  
  98.  
  99.         foreach (DataRow dr in tb.Rows)  
  100.         {  
  101.             sb.Append("<tr><td>");  
  102.             sb.Append(dr["name"]);// 獲取某列數據 dr["列名"]  
  103.             sb.Append("</td><td>");  
  104.             sb.Append(dr["class"]);  
  105.             sb.Append("</td></tr>");  
  106.         }         
  107.         sb.Append("</table>");  
  108.         return sb.ToString();      
  109.     }  
  110.     protected void lbtnFirst_Click(object sender, EventArgs e)  
  111.     {        
  112.         Session["pageIndex"] = 1;  
  113.         BindRepeater();  
  114.     }  
  115.     protected void lbtnPre_Click(object sender, EventArgs e)  
  116.     {         
  117.         if (Convert.ToInt32(Session["pageIndex"]) > 1)  
  118.             Session["pageIndex"] = Convert.ToInt32(Session["pageIndex"]) - 1;  
  119.         else  
  120.             Session["pageIndex"] = 1; //當前已經是第一頁  
  121.         BindRepeater();  
  122.     }  
  123.     protected void lbtnNext_Click(object sender, EventArgs e)  
  124.     {  
  125.         if (Convert.ToInt32(Session["pageIndex"]) < totalPageCount)  
  126.         Session["pageIndex"] = Convert.ToInt32(Session["pageIndex"]) + 1;  
  127.         else  
  128.         Session["pageIndex"] = totalPageCount; //當前已經是最後一頁  
  129.         BindRepeater();  
  130.     }  
  131.     protected void lbtnLast_Click(object sender, EventArgs e)  
  132.     {          
  133.         Session["pageIndex"] = totalPageCount;  
  134.         BindRepeater();  
  135.     }  
  136. }  
相關文章
相關標籤/搜索