sql通用的存储过程

QUOTED_IDENTIFIER ON GO ALTER proc [dbo].[UpPagerSingle]

@ReturnFields Varchar(500)='*',--搜索表的字段,比如:’id,datatime,job‘,用逗号隔开

@TableName Varchar(30), --搜索的表名 @Where Varchar(1000)='',--搜索条件,这里不用写where,比如:job=’teacher‘and class='2'

@Orderfld Varchar(200)='', --排序,可以使用多字段排序但主键字段必需在最前面.也可以不写,比如:order by class asc @PageIndex int=1, --页号

@PageSize int=20 --每页显示数 as

declare  @RecordCount int=0 declare @TmpSelect      NVarchar(max)  declare @Tmp     NVarchar(600)

set nocount on--关闭计数

if @Where!='' set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' where '+@Where

else

set @TmpSelect='select @RecordCount=count(*) from '+@TableName+''

execute sp_executesql @TmpSelect,    --执行上面的sql语句 N'@RecordCount int OUTPUT' ,   --执行输出数据的sql语句,output出总记录数

@RecordCount  OUTPUT

/*判断页数是否正确*/

if (@PageIndex - 1) * @PageSize > @RecordCount   --页号大于总页数,返回错误

begin

if(@RecordCount%@PageSize)>0

set @PageIndex=@RecordCount/@PageSize+1

else   set @PageIndex=@RecordCount/@PageSize end set nocount off--打开计数

if @Where <> ''

begin

set @TmpSelect = 'select * from (select row_number() over('+@Orderfld+' ) rn,'+@ReturnFields+' from ' +@TableName+' where '+@Where+')tb where rn >'  + convert(nvarchar(50),(@PageIndex-1)*@PageSize) +' and rn <= '+convert(nvarchar(50),@PageIndex*@PageSize)

end

else

begin

set @TmpSelect = 'select * from (select row_number() over('+@Orderfld+' ) rn,'+@ReturnFields+' from ' +@TableName+')tb where rn >'  + convert(nvarchar(50),(@PageIndex-1)*@PageSize) +' and rn <= '+convert(nvarchar(50),@PageIndex*@PageSize)

end

execute sp_executesql @TmpSelect

SELECT  @RecordCount As RecordCount

上一篇:解决Eclipse异常关闭后重启报 org.eclipse.swt.SWTException: Invalid thread access 的问题


下一篇:VMware 9 安装 Mac OS X 10.8 Mountain Lion 图文全程