-- ============================================= -- Author: 蜘蛛王 -- Create date: 2015-10-29 -- Description: 可搜索 可排序 可分页存储过程 适用于sql2008以上 -- (非常重要,请认真使用) -- ============================================= create PROCEDURE dbo.list ( @table varchar(1000),--表名或视图表 (必须) @orderby varchar(1000),--排序字段 (必须) @fields varchar(max)=‘*‘,--欲选择字段列表 (可选) @pageindex int=1,--页号,从1开始 (可选) @pagesize int=20,--页尺寸 (可选) @where nvarchar(max) = N‘‘,--条件 (可选) @IsCount bit = 1 -- 返回记录总数, 非 0 值则返回 (可选) ) AS BEGIN SET NOCOUNT ON declare @sqlstr nvarchar(max) set @sqlstr=‘‘ set @orderby = ‘ order by ‘ + @orderby if @where<>N‘‘ set @where = ‘ Where ‘ + @where --对第一页可以直接用top if @pageindex=1 begin set @sqlstr = ‘select top ‘ + CONVERT(varchar(10),@pagesize) + ‘ ‘ + @fields + ‘ from ‘ + @table + @where + @orderby end else begin set @sqlstr = ‘with temptbl as (‘ + ‘ SELECT ROW_NUMBER() OVER (‘+ @orderby +‘) AS Row, ‘ + @fields + ‘ from ‘ + @table + @where + ‘) SELECT ‘+ @fields + ‘ FROM temptbl where Row between ‘ + CONVERT(varchar(10),(@pageindex-1)*@pagesize+1) + ‘ and ‘ + CONVERT(varchar(10),(@pageindex-1)*@pagesize+@pagesize) end if @IsCount!=0 set @sqlstr = @sqlstr + ‘;select count(1) from ‘ + @table + @where execute(@sqlstr) END
--测试代码 exec list @table=‘dl_QQ‘,@orderby=‘iid desc‘,@IsCount=1, @pageindex =2, @fields=‘iid,qq‘, @where=‘ iid <30 ‘ exec list @table=‘dl_QQ‘,@orderby=‘iid desc‘,@IsCount=1, @pageindex =1, @fields=‘iid,qq‘, @where=‘ iid <30 ‘
时间: 2024-10-05 04:25:18