微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

分页 SQLServer存储过程

/*--用存储过程实现的分页程序

 

显示指定表、视图、查询结果的第X页

 

对于表中主键或标识列的情况,直接从原表取数查询,其它情况使用临时表的方法

 

如果视图或查询结果中有主键,不推荐此方法

 

--邹建 2003.09--exec p_show '地区资料'

 

exec p_show '地区资料',5,3,'地区编号,地区名称,助记码','地区编号'

 

--因为要顾及通用性,所以对带排序的查询语句有一定要求.如果先排序,再出结果.就是:

 

exec p_show 'select top 100 percent * from 地区资料 order by 地区名称','地区名称'

 

--查询语句加上:top 100 percent //top时

 

if exists  and OBJECTPROPERTY = 1)

 

drop procedure .

 

GO

 

CREATE Proc p_show

 

@QueryStr nvarchar,--表名、视图名、查询语句

 

@PageSize int=10,--每页的大小

 

@PageCurrent int=1,--要显示的页

 

@FdShow nvarchar ='',--要显示的字段列表,如果查询结果有标识字段,需要指定此值,且不包含标识字段

 

@FdOrder nvarchar ='' --排序字段列表

 

as

 

declare @FdName nvarchar --表中的主键或表、临时表中的标识列名

 

,@Id1 varchar,@Id2 varchar --开始和结束的记录号

 

,@Obj_ID int --对象ID

 

--表中有复合主键的处理

 

declare @strfd nvarchar --复合主键列表

 

,@strjoin nvarchar --连接字段

 

,@strwhere nvarchar --查询条件

 

select @Obj_ID=object_id

 

,@FdShow=case isnull when '' then ' *' else ' '+@FdShow end

 

,@FdOrder=case isnull when '' then '' else ' order by '+@FdOrder end

 

,@QueryStr=case when @Obj_ID is not null then ' '+@QueryStr else '  a' end

 

--如果显示第一页,可以直接用top来完成

 

if @PageCurrent=1

 

begin

 

select @Id1=cast)

 

exec

 

return

 

end

 

--如果是表,则检查表中是否有标识更或主键

 

if @Obj_ID is not null and objectproperty=1

 

begin

 

select @Id1=cast)

 

,@Id2=cast*@PageSize as varchar)

 

select @FdName=name from syscolumns where id=@Obj_ID and status=0x80

 

if @@rowcount=0 --如果表中无标识列,则检查表中是否有主键

 

begin

 

if not exists

 

goto lbusetemp --如果表中无主键,则用临时表处理

 

select @FdName=name from syscolumns where id=@Obj_ID and colid in))

 

if @@rowcount>1 --检查表中的主键是否为复合主键

 

begin

 

select @strfd='',@strjoin='',@strwhere=''

 

select @strfd=@strfd+','

 

,@strjoin=@strjoin+' and a.=b.'

 

,@strwhere=@strwhere+' and b. is null'

 

from syscolumns where id=@Obj_ID and colid in))

 

select @strfd=substring

 

,@strjoin=substring

 

,@strwhere=substring

 

goto lbusepk

 

end

 

end

 

end

 

else

 

goto lbusetemp

 

/*--使用标识列或主键为单一字段的处理方法--lbuseidentity:

 

exec'+@FdOrder

 

)

 

return

 

/*--表中有复合主键的处理方法--lbusepk:

 

exec a

 

left join  b on '+@strjoin+'

 

where '+@strwhere+') a'

 

)

 

return

 

/*--用临时表处理的方法--lbusetemp:

 

select @FdName=''

 

,@Id1=cast as varchar)

 

,@Id2=cast)

 

exec,'+@FdShow+'

 

into #tb from'+@QueryStr+@FdOrder+'

 

select '+@FdShow+' from #tb where '+@FdName+' between '

 

+@Id1+' and '+@Id2

 

)

 

GO

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐