zoukankan      html  css  js  c++  java
  • 存储过程分页(二)

    CREATE PROCEDURE dbo.CreateSimple

    2(

    3 @PageIndex int,

    4 @PageSize int

    5)

    6AS

    7BEGIN

    8 --定义三个变量:

    9 -- @PageLowerBound :所取出记录的下限.

    10 -- @PageUpperBound: 所要取出记录的上限.

    11 -- @TotalRecords: 返回记录总数,主要用于页面的计算.

    12 DECLARE @PageLowerBound int

    13 DECLARE @PageUpperBound int

    14 DECLARE @TotalRecords int

    15

    16 --计算上下限的值.

    17 SET @PageLowerBound=@PageIndex * @PageSize

    18 SET @PageUpperBound=@PageLowerBound+@PageSize-1

    19

    20--创建临时表:

    21--IndexId是标识,自动增长1;

    22--SimpleId由数据表[Simple]填充;

    23 CREATE TABLE #PageIndexForSimple

    24 (

    25 IndexId int identity(1,1) NOT NULL,

    26 SimpleId int

    27 )

    28--填充临时表

    29 INSERT INTO #PageIndexForSimple(SimpleId)

    30 SELECT s.[SimpleId]

    31 FROM [Simple] s

    32 --这里可以加WHERE condition和ODER BY语句

    33

    34 --取得记录总数,其实影响行数就是记录总数

    35 SELECT @TotalRecords=@@ROWCOUNT

    36

    37 --获取我们所要的记录.

    38 SELECT s.*

    39 FROM [Simple] s,#PageIndexForSimple p

    40 WHERE s.[SimpleId]=p.[SimpleId]

    41 AND p.[IndexId]>=@PageLowerBound

    42 AND P.[IndexId]<=@PageUpperBound

    43 ORDER BY s.[Simple]

    44

    45 --返回记录总数.

    46 RETURE @TotalRecords

    47END

    由上面的注释就能看懂了,呵呵,既然写到这里也把程序的代码写出来:

    1Public List<Simple> GetSimple(int pageIndex,int pageIndex,out int totalRecords){

    2 List<Simple> entity=new List<Simple>();

    3 SqlParameter[]param=new SqlParameter[]{

    4 new SqlParameter("@PageIndex",SqlDbType.Int),

    5 new SqlParameter("@PageSize",SqlDbType.Int),

    6 new SqlParameter("@ReturnValue",SqlDbType.Int),

    7 };

    8 param[0].Value=pageIndex;

    9 param[1].Value=pageSize;

    10 param[2].Direction = ParameterDirection.ReturnValue;

    11 SqlDataReader reader=SqlHelper.ExecuteReader(CommandType.StoredProcedure, "GetSimple", param);

    12 While(reader.Read()){

    13 entity.Add(GetSimpleEntity(reader))

    14 }

    15 reader.Close();

    16 try{

    17 totalRecords=(int)param[2].Value;

    18 }catch{}

    19 return entity;

    20}

    上面的一些函数是自己写的:

    SqlHelper类:简化数据库查询类.

    GetSimpleEntity(SqlDataReader reader):由于经常在项目中会用到好基础实体类的获取,所以单独写一个私有函数,以便重用;

    值得注意的是获取总的记录数时可能类型为DbNull而导致错误.

  • 相关阅读:
    洛谷 2846 (线段树)
    Conclusion
    codevs 2495 水叮当的舞步IDA*
    1247 排排站 USACO(查分+hash)
    洛谷 1373 小a和uim之大逃离
    noip 2012 疫情控制
    poj 1780 code(欧拉路)
    uva 1391 Astronauts(2-SAT)
    uva 1146 Now or late (暴力2-SAT)
    uva 11324 The Largest Clique (Tarjan+记忆化)
  • 原文地址:https://www.cnblogs.com/weihengblogs/p/3580746.html
Copyright © 2011-2022 走看看