码迷,mamicode.com
首页 > 数据库 > 详细

Sql万能分页代码

时间:2018-07-28 13:47:08      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:查询条件   int   HERE   erb   name   记录   sel   tab   lse   

go  ----万能分页代码
create procedure [dbo].[sp_datapager]
@pagesize int,--每一页的大小
@pageindex int,--页码数
@tablename varchar(Max),--表的名称
@keycolumn varchar(20),---主键id
@columns varchar(200),--要查询出列的名称
@where varchar(200),---查询条件
@orderby varchar(100),---排序方式
@recordcount int out--输出参数,非0则返回要查询表的总记录数

as
declare @sql nvarchar(3000)
declare @rcsql nvarchar(1000)
set @rcsql=‘select @rc=count(*) from ‘+@tablename
set @sql=‘select top ‘+convert(varchar(3),@pagesize)+‘ ‘+ @columns+‘ from ‘+
@tablename +‘ where ‘+@keycolumn+‘ not in(select top ‘+
convert(varchar(10),(@pageindex-1)*@pagesize)+‘ ‘+@keycolumn+
‘ from ‘+@tablename+‘)‘
if (@where!=‘‘)
begin
set @rcsql=‘select @rc=count(*) from ‘+@tablename+‘ where ‘+@where
set @sql=‘select top ‘+convert(varchar(3),@pagesize)+ @columns+‘ from ‘+
@tablename +‘ where ‘+@keycolumn+‘ not in(select top ‘+
convert(varchar(10),(@pageindex-1)*@pagesize)+‘ ‘+@keycolumn+
‘ from ‘+@tablename+‘ where ‘+@where+‘) and ‘+@where
end
if (@orderby!=‘‘)
begin
if (@where!=‘‘)
begin
set @sql=‘select top ‘+convert(varchar(3),@pagesize)+ @columns+‘ from ‘+
@tablename +‘ where ‘+@keycolumn+‘ not in(select top ‘+
convert(varchar(10),(@pageindex-1)*@pagesize)+‘ ‘+@keycolumn+
‘ from ‘+@tablename+‘ where ‘+@where+‘ order by ‘+@orderby+‘) and ‘+
@where+‘ order by ‘ +@orderby
end
else
begin
set @sql=‘select top ‘+convert(varchar(3),@pagesize)+ @columns+‘ from ‘+
@tablename +‘ where ‘+@keycolumn+‘ not in(select top ‘+
convert(varchar(10),(@pageindex-1)*@pagesize)+‘ ‘+@keycolumn+
‘ from ‘+@tablename+‘ order by ‘+@orderby+‘)‘+‘ order by ‘ +@orderby
end

end
declare @param nvarchar(100)
set @param=‘@rc int output‘
exec sp_executesql @sql
exec sp_executesql @rcsql,@param,@rc=@recordcount output

Sql万能分页代码

标签:查询条件   int   HERE   erb   name   记录   sel   tab   lse   

原文地址:https://www.cnblogs.com/wslpf/p/9381371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!