原文地址:http://dzsnowdrop.blog.163.com/blog/static/164932582201062792841678/
存储过程实现分页
1 -------------------------------------------------------以下代码为存储过程代码 2 3 CREATE procedure News_Class 4 5 --资讯新闻百万级分页 6 7 ( 8 9 @StrWhere varchar(100),--条件 10 11 @PageSize int, --页面大小 12 13 @PageIndex int --页面索引 14 15 ) 16 17 AS 18 19 declare @strSQL varchar(2000) -- 主语句 20 21 declare @strCountSQL varchar(2000) -- 总记录主语句 22 23 declare @strTmp varchar(1000) -- 临时变量 24 25 Set @strTmp =" Select top " + str(@PageSize) + " Title,AddTime from Tb_News " --此处注意,需几个字段读几个字段 26 27 if @StrWhere<>'' 28 29 Begin 30 31 Set @strSQL=@strTmp + " where ID < (select min(ID) from (select top " + str((@PageIndex-1)*@PageSize)+" ID from Tb_News Where "+@StrWhere+" order by ID desc) as tblTmp ) and "+@StrWhere+" order by ID desc" 32 33 set @strCountSQL="select count(ID) as countx from Tb_News Where "+@StrWhere+" " 34 35 End 36 37 else 38 39 Begin 40 41 Set @strSQL=@strTmp + " where ID < (select min(ID) from (select top " + str((@PageIndex-1)*@PageSize)+" ID from Tb_News order by ID desc) as tblTmp ) order by ID desc" 42 43 set @strCountSQL="select count(ID) as countx from Tb_News " 44 45 End 46 47 if @PageIndex = 1 48 49 if @StrWhere<>'' 50 51 Begin 52 53 Set @strSQL=@strTmp +" Where "+@StrWhere+" order by ID desc" 54 55 End 56 57 else 58 59 Begin 60 61 Set @strSQL=@strTmp +" order by ID desc" 62 63 End 64 65 exec (@strSQL) 66 67 exec (@strCountSQL) 68 69 GO