SQL分页存储过程

-- =============================================
-- Author:		xyy
-- Create date: 2011-04-06
-- Description:	分页,所有参数中除了@strwhere中可以而带方括号([]),其他均不可以带
-- =============================================
CREATE PROCEDURE [dbo].[sp_All_Pager]
	@tblName nvarchar(255),--表名
	@fldNames nvarchar(1000)='*',--字段列表(默认所有字段)
	@fldOrderName nvarchar(255),--主键字段(排序用)
	@orderType bit =0,--排序类型,非0则降序(默认升序)
	@pageIndex int=1,--页码
	@pageSize int =20,--页大小
	@strWhere nvarchar(1500)='',--查询条件,不带where
	@limitCount int =5000, --限制最多取5000条数据
	@totalCount int output --总记录数
AS
BEGIN
	SET NOCOUNT ON;
	declare @strSQL nvarchar(4000)--主语句
	declare @strTable nvarchar(500)--主查询临时表
	declare @strOrderSQL nvarchar(1000)--总数查询语句
	declare @strOutParam nvarchar(500)--输出参数
	declare @strTmp nvarchar(255)--临时分页字句 max 和min
	declare @strOrder nvarchar(255)--排序参数
		
	--设置排序
	if(@orderType != 0)
	begin
		set @strTmp = ' <(select min '
		set @strOrder = ' order by [' + @fldOrderName +'] desc'
	end
	else
	begin
		set @strTmp = ' >(select max '
		set @strOrder = ' order by [' + @fldOrderName +'] asc'
	end
	--设置主查询临时表
	if(@strWhere!='')
		set @strTable='(select top '+STR(@limitCount)+' '+@fldNames+' from ['+@tblName+'] where '+@strWhere+') as tmpTable'
    else
		set @strTable='(select top '+STR(@limitCount)+' '+@fldNames+' from ['+@tblName+']) as tmpTable'
	--设置总数查询语句和主语句
	set @strOrderSQL=N'select @totalCountOut=count(1) from '+@strTable
	set @strOutParam=N'@totalCountOut int output'
	if (@pageIndex = 1)
		set @strSQL = 'select top ' + str(@pageSize) +' '+@fldNames+ ' from ' + @strTable + @strOrder
	else
		set @strSQL = 'select top ' + str(@PageSize) +' '+@fldNames+ ' from ' + @strTable + ' where [' + @fldOrderName + ']' + @strTmp + '(['+ @fldOrderName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldOrderName + '] from ' + @strTable + @strOrder + ') as tblTmp) ' + @strOrder
	exec sp_executesql @strOrderSQL,@strOutParam,@totalCountOut=@totalCount output
	exec sp_executesql @strSQL
END

GO


编程技巧