看到大家对数据库分页有研究,也分享个本人的

一个完整的sql语句分解开来,也就分文字段,表名或表连接,条件,排序,分组一共五部分

select a.id,a.name,b.id as bid,b.name as bname

from 表1 a inner join 表2 b

where a.id > 1

order by a.id asc

如上述sql语句分解开来由以下四部分组成

字段部分:a.id,a.name,b.id as bid,b.name as bname

表部分:表1 a inner join 表2 b

条件部分:a.id > 1

还有排序部分 a.id asc

 

本人sql分页存储过程

  1. CREATE    proc [dbo].[pageView]
  2. @pIndex int,--页码
  3. @pSize int,--每页行数
  4. @id varchar(30),--主键ID
  5. @Fields varchar(4000),---字段
  6. @tabName varchar(4000),--表名,和要连接的表以及关系
  7. @where varchar(4000)='',--条件
  8. @sort varchar(4000)=''--排序字段
  9. as
  10. create table #ls
  11. (row int identity(1,1),
  12. aid int
  13. )
  14. create table #ls1
  15. (
  16. row1 int identity(1,1),
  17. row int,
  18. aid int
  19. )
  20. declare @start int
  21. declare @end int
  22. declare @str varchar(8000)
  23. set @end=@pIndex * @pSize
  24. set @start=@end-@pSize+1
  25. set @str='select count('+@id +') as rowcounts from '+@tabName --+ ' where '+@where +' order by '+@sort
  26. if len(@where)> 0
  27.  set @str =@str + ' where '+@where
  28. exec (@str)
  29. set @str='insert into #ls(aid) select top '+str(@end)+' '+@id +' from '+@tabName --+ ' where '+@where +' order by '+@sort
  30. if len(@where)> 0
  31.  set @str =@str + ' where '+@where
  32. if len(@sort)>0
  33.  set @str=@str + ' order by ' +@sort
  34. exec (@str)
  35. insert into #ls1(row,aid)
  36. select #ls.row,#ls.aid from #ls where #ls.row between @start and @end
  37. drop table #ls
  38. --select * from #ls1
  39. set @str='select #ls1.row1,#ls1.row,'+@Fields+' from '+ @tabName + ' join #ls1 on #ls1.aid='+@id +' order by #ls1.row1'
  40. exec(@str)

 

 

 

可以很快的对数据进行分页,并且返回总记录数,每页序号,总序号以及数据来,

 

posted @ 2012-10-25 17:27  一叶兰舟飘  阅读(226)  评论(0编辑  收藏  举报