看到大家对数据库分页有研究,也分享个本人的
一个完整的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分页存储过程
- CREATE proc [dbo].[pageView]
- @pIndex int,--页码
- @pSize int,--每页行数
- @id varchar(30),--主键ID
- @Fields varchar(4000),---字段
- @tabName varchar(4000),--表名,和要连接的表以及关系
- @where varchar(4000)='',--条件
- @sort varchar(4000)=''--排序字段
- as
- create table #ls
- (row int identity(1,1),
- aid int
- )
- create table #ls1
- (
- row1 int identity(1,1),
- row int,
- aid int
- )
- declare @start int
- declare @end int
- declare @str varchar(8000)
- set @end=@pIndex * @pSize
- set @start=@end-@pSize+1
- set @str='select count('+@id +') as rowcounts from '+@tabName --+ ' where '+@where +' order by '+@sort
- if len(@where)> 0
- set @str =@str + ' where '+@where
- exec (@str)
- set @str='insert into #ls(aid) select top '+str(@end)+' '+@id +' from '+@tabName --+ ' where '+@where +' order by '+@sort
- if len(@where)> 0
- set @str =@str + ' where '+@where
- if len(@sort)>0
- set @str=@str + ' order by ' +@sort
- exec (@str)
- insert into #ls1(row,aid)
- select #ls.row,#ls.aid from #ls where #ls.row between @start and @end
- drop table #ls
- --select * from #ls1
- set @str='select #ls1.row1,#ls1.row,'+@Fields+' from '+ @tabName + ' join #ls1 on #ls1.aid='+@id +' order by #ls1.row1'
- exec(@str)
可以很快的对数据进行分页,并且返回总记录数,每页序号,总序号以及数据来,