USE [Test] GO /****** Object: StoredProcedure [dbo].[sp_Common_GetListByPage] Script Date: 01/11/2017 16:25:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[GetListPage] @tablename varchar(200), -- 需要分页的表 @GetCols varchar(500) , -- 需要查询的列 @sortName varchar(50), -- 排序的列 @PageSize int, -- 每一页显示的数据 @PageIndex int, -- 当前页码 @doCount bit, -- 返回记录总数, 非 0 值则返回 @OrderType bit, -- 设置排序类型, 非 0 值则降序 @strWhere varchar(1500) -- 查询条件 (注意: 不要加 where) AS declare @strSQL varchar(5000) -- 主语句 declare @strTmp varchar(110) -- 临时变量 declare @strOrder varchar(400) -- 排序类型 --@doCount不是0,就执行总数统计 if @doCount != 0 begin if @strWhere !='' set @strSQL = 'select count(*) as Total from ' + @tablename + ' where '+ @strWhere else set @strSQL = 'select count(*) as Total from ' + @tablename end --@doCount为0的情况 else begin --@OrderType不是0,就执行降序 if @OrderType != 0 begin set @strTmp = '<(select min' set @strOrder = ' order by ' + @sortName +' desc' end else begin set @strTmp = '>(select max' set @strOrder = ' order by ' + @sortName +' asc' end --如果是第一页就执行以下代码 if @PageIndex = 1 begin if @strWhere != '' set @strSQL = 'select top ' + str(@PageSize) +' '+@GetCols+ ' from ' + @tablename + ' where ' + @strWhere + ' ' + @strOrder else set @strSQL = 'select top ' + str(@PageSize) +' '+@GetCols+ ' from '+ @tablename + ' '+ @strOrder end else --不是第一页的处理 begin set @strSQL = 'select top ' + str(@PageSize) +' '+@GetCols+ ' from ' + @tablename + ' where ' + @sortName + ' ' + @strTmp + '('+ @sortName + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' '+ @sortName + ' from ' + @tablename + ' ' + @strOrder + ') as tblTmp)'+ @strOrder if @strWhere != '' set @strSQL = 'select top ' + str(@PageSize) +' '+@GetCols+ ' from ' + @tablename + ' where ' + @sortName + ' ' + @strTmp + '(' + @sortName + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' ' + @sortName + ' from ' + @tablename + ' where ' + @strWhere + ' ' + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder end end exec (@strSQL) GO