万能的分页存储过程,需求传入任意SQL语句、开始页码(0开始)、页的大小,返回记录集。SQL语句中可以有排序、分组等子句,如何实现,之前找到一个可以实现类似功能,但SQL语句中有排序子句的时候就出错。如何实现?
------解决思路----------------------
CREATE PROCEDURE [dbo].[Paging_Custom]
(
@Tables varchar(1000),
@PK varchar(100),
@Sort varchar(200) = NULL,
@isAscending bit=1,
@PageNumber int = 1,
@PageSize int = 10,
@Fields varchar(8000) = '*',
@Filter varchar(max) = NULL,
@Group varchar(1000) = NULL
)
AS
DECLARE @strFilter varchar(max)
DECLARE @strSimpleFilter varchar(max)
DECLARE @strGroup varchar(max)
DECLARE @SortTable varchar(100)
DECLARE @SortName varchar(100)
DECLARE @strPKColumn varchar(100)
DECLARE @strSortColumn varchar(200)
DECLARE @operator char(2)
/*Set filter & group variables.*/
IF @Filter IS NOT NULL AND @Filter != ''
BEGIN
SET @strFilter = ' WHERE ' + @Filter + ' '
SET @strSimpleFilter = ' AND ' + @Filter + ' '
END
ELSE
BEGIN
SET @strSimpleFilter = ' '
SET @strFilter = ' '
END
IF @Group IS NOT NULL AND @Group != ''
SET @strGroup = ' GROUP BY ' + @Group + ' '
ELSE
begin
SET @strGroup = ' '
end
/*count*/
--exec ('select count(*) from ' +@Tables+' '+ @strFilter)
/*operator and asc_desc*/
declare @strAsc_Des varchar(50)
IF @isAscending = 0
BEGIN
SET @operator = '<='
SET @strAsc_Des = ' Desc '
END
ELSE
BEGIN
SET @operator = '>='
SET @strAsc_Des = ' ASC '
END
/*Set sorting variables.*/
/*Default Sorting*/
IF @Sort IS NULL OR @Sort= ''
BEGIN
SET @Sort = @PK
END
SET @strSortColumn = @Sort
IF CHARINDEX('.', @PK) > 0
BEGIN
SET @strPKColumn = SUBSTRING(@PK, CHARINDEX('.',@PK) + 1, LEN(@PK))
END
ELSE
BEGIN
SET @strPKColumn = @PK
END
IF CHARINDEX('.', @strSortColumn) > 0
BEGIN
SET @SortTable = SUBSTRING(@strSortColumn, 0, CHARINDEX('.',@strSortColumn))
SET @SortName = SUBSTRING(@strSortColumn, CHARINDEX('.',@strSortColumn) + 1, LEN(@strSortColumn))
END
ELSE
BEGIN
SET @SortTable = @Tables
SET @SortName = @strSortColumn
END
/*Handle complex table*/
--Be join table,so get the left table
IF CHARINDEX(' join ',@Tables) > 0
BEGIN
SET @SortTable=SUBSTRING(ltrim(@Tables),0,CHARINDEX(' ',@Tables))
SET @strSortColumn = @SortTable+'.'+@SortName
END
/*Check the sortColumn if be Unique*/
IF @SortName <> @strPKColumn
BEGIN
DECLARE @tempName varchar(100)
SELECT @tempName=b.name
FROM sysobjects a INNER JOIN
sysobjects b ON a.id = b.parent_obj
INNER JOIN sysindexes c ON b.name = c.name INNER JOIN
sysindexkeys d ON c.id = d.id AND c.indid = d.indid INNER JOIN
syscolumns e ON d.id = e.id AND d.colid = e.colid
WHERE (b.xtype = 'UQ') AND (a.name = @SortTable) AND (e.name = @SortName)
IF @tempName IS NULL
BEGIN
GOTO Paging_Not_In
END
END
Paging_RowCount:
/*Find the @SORT type*/
DECLARE @type varchar(100)
DECLARE @prec int
SELECT @type=t.name, @prec=c.prec
FROM sysobjects o
JOIN syscolumns c on o.id=c.id
JOIN systypes t on c.xusertype=t.xusertype
WHERE o.name = @SortTable AND c.name = @SortName
IF CHARINDEX('char', @type) > 0
SET @type = @type + '(' + CAST(@prec AS varchar) + ')'
DECLARE @strPageSize varchar(50)
DECLARE @strStartRow varchar(50)
/*Default Page Number*/
--IF @PageNumber < 1
--SET @PageNumber = 1
/*Set paging variables.*/
SET @strPageSize = CAST(@PageSize AS varchar(50))
SET @strStartRow = CAST(((@PageNumber - 1)*@PageSize + 1) AS varchar(50))
/*Execute dynamic query '
SET ROWCOUNT ' + @strPageSize +*/
DECLARE @ddsql NVARCHAR(max)--,@SortColumn VARCHAR(100),@RETURNFILED NVARCHAR(4000)
--SET @RETURNFILED=N'@SortColumn ' + @type+ ' output'
--
--SET @ddsql='
--SET ROWCOUNT 100 SELECT @SortColumn='+@strSortColumn+' FROM (
--SELECT ID=row_number()over(order by '+@Sort+ @strAsc_Des+'),' + @strSortColumn + ' FROM ' + @Tables + @strFilter + ' ' + @strGroup +
--') AS A WHERE A.ID='+@strStartRow
--EXEC sp_executesql @ddsql,@RETURNFILED,@SortColumn OUTPUT--输出变量
--PRINT @SortColumn
SET @ddsql='DECLARE @SortColumn ' + @type + '
SELECT @SortColumn='+@strSortColumn+' FROM (
SELECT ID=row_number()over(order by '+@Sort+ @strAsc_Des+'),' + @strSortColumn + ' FROM ' + @Tables + @strFilter + ' ' + @strGroup +
') AS A WHERE A.ID='+@strStartRow+'
SET ROWCOUNT ' + @strPageSize +
'SELECT ' + @Fields + ' FROM ' + @Tables + ' WHERE ' + @strSortColumn + @operator + ' @SortColumn ' +
@strSimpleFilter + ' ' + @strGroup + ' ORDER BY ' + @Sort + @strAsc_Des
PRINT @ddsql
exec (@ddsql)
--EXEC('DECLARE @SortColumn ' + @type + '
--SET ROWCOUNT ' + @strStartRow +
-- ' SELECT @SortColumn=' + @strSortColumn + ' FROM ' + @Tables + @strFilter + ' ' + @strGroup +
-- ' ORDER BY ' + @Sort + @strAsc_Des+' SET ROWCOUNT ' + @strPageSize +
-- 'SELECT ' + @Fields + ' FROM ' + @Tables + ' WHERE ' + @strSortColumn + @operator + ' @SortColumn ' +
-- @strSimpleFilter + ' ' + @strGroup + ' ORDER BY ' + @Sort + @strAsc_Des )
/* 支持CLR函数
EXEC('
SET ROWCOUNT 0 ' + ' ' +
'if object_id('+''''+'tempyww'+''''+') is not null begin drop table tempyww end SELECT ' + @Fields + ' into tempyww FROM ' + @Tables + ' '+@strFilter+' select top '+@strPageSize+' * from tempyww WHERE ' + @strSortColumn + @operator +'''' + @SortColumn+''
'' + ' ' + @strGroup + ' ORDER BY ' + @Sort + @strAsc_Des )
*/
RETURN
Paging_Not_In:
DECLARE @strTotalNum int
SET @strTotalNum = (@PageNumber - 1)*@PageSize
--如果排序是索引列则notin方法会非常缓慢
--下限以10000为界
--if (@strTotalNum > 10000)
--begin
--declare @TotalCount int
--declare @SQL nvarchar(100)
--set @SQL = 'select @TotalCount = count(*) from ' +@Tables+' '+ @strFilter
--exec sp_executesql @SQL,N'@TotalCount int output',@TotalCount out
--上限以3/4为界
--if (@strTotalNum/@TotalCount < 0.75) goto Paging_ASCD_ESC
--end
--第一页
IF @strTotalNum = 0
begin
exec('select top '+@PageSize+' '+@Fields+' from '+@Tables+' '+@strFilter+ @strGroup + ' ORDER BY ' + @Sort + @strAsc_Des+ ','+ @PK + @strAsc_Des)
PRINT '1'
end
ELSE
begin
exec('select top '+@PageSize+' '+@Fields+' from '+@Tables+' where '
+@PK+' not in(select top '
+@strTotalNum+' '+@PK+' from '+@Tables+' '+@strFilter+ @strGroup +
' ORDER BY ' + @Sort + @strAsc_Des + ','+ @PK + @strAsc_Des
+') '+@strSimpleFilter+ @strGroup + ' ORDER BY ' + @Sort + @strAsc_Des + ','+ @PK + @strAsc_Des)
PRINT '2'
end
RETURN
Paging_ASCD_ESC:
------解决思路----------------------
我修改了你的如下
ALTER PROCEDURE [SelectPages]
(
@p1 varchar(8000), --SQL查询语句
@p2 bigint, --页的大小
@p3 bigint, --第几面,从0开始
@p4 varchar(8000), --排序子句(最终列名,且不函表别名)
@recordTotal INT OUTPUT --输出记录总数
)
as
begin
set nocount on
declare @tsql varchar(8000)
DECLARE @tempCount NVARCHAR(1000)
--declare @tp1 varchar(8000)
set @p1 = REPLACE(@p1,'@','''')
--输出参数为总记录数
SET @tempCount = 'SELECT @recordTotal = COUNT(*) FROM ('+@p1+ ') AS my_temp'
EXECUTE sp_executesql @tempCount,N'@recordTotal INT OUTPUT',@recordTotal OUTPUT
IF @p4=''
SET @p4='getdate()'
select @tsql='with t as '
+'(select row_number() over(order by '+@p4+') ''rn'' ,*'
+' from ('+@p1+') y) '
+'select top '+rtrim(@p2)+ ' * '
+'from t '
+'where rn>'+rtrim(@p2*@p3)
PRINT @tsql
exec(@tsql)
END
------解决思路----------------------
问下 这个分页是干嘛的 百度了下说分页就是用row_number()或者in,not int 实现就OK 了.你这个分页指的是在前台应用程序里面实现翻页吗?(就是每页里面显示多少行。)
------解决思路----------------------
CREATE PROC sp_PageView
@tbname sysname, --要分页显示的表名
@FieldKey nvarchar(1000), --用于定位记录的主键(惟一键)字段,可以是逗号分隔的多个字段
@PageCurrent int=1, --要显示的页码
@PageSize int=10, --每页的大小(记录数)
@FieldShow nvarchar(1000)='', --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
@FieldOrder nvarchar(1000)='', --以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC
用于指定排序顺序
@Where nvarchar(1000)='', --查询条件
@PageCount int OUTPUT --总页数
AS
SET NOCOUNT ON
--检查对象是否有效
IF OBJECT_ID(@tbname) IS NULL
BEGIN
RAISERROR(N'对象"%s"不存在',1,16,@tbname)
RETURN
END
IF OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTable')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsView')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTableFunction')=0
BEGIN
RAISERROR(N'"%s"不是表、视图或者表值函数',1,16,@tbname)
RETURN
END
--分页字段检查
IF ISNULL(@FieldKey,N'')=''
BEGIN
RAISERROR(N'分页处理需要主键(或者惟一键)',1,16)
RETURN
END
--其他参数检查及规范
IF ISNULL(@PageCurrent,0)<1 SET @PageCurrent=1
IF ISNULL(@PageSize,0)<1 SET @PageSize=10
IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
IF ISNULL(@FieldOrder,N'')=N''
SET @FieldOrder=N''
ELSE
SET @FieldOrder=N'ORDER BY '+LTRIM(@FieldOrder)
IF ISNULL(@Where,N'')=N''
SET @Where=N''
ELSE
SET @Where=N'WHERE ('+@Where+N')'
--如果@PageCount为NULL值,则计算总页数(这样设计可以只在第一次计算总页数,以后调用时,把总页数传回给存储过程,避免再次计算总页数,对于不想计算总页数的处理而言,可以给@PageCount赋值)
IF @PageCount IS NULL
BEGIN
DECLARE @sql nvarchar(4000)
SET @sql=N'SELECT @PageCount=COUNT(*)'
+N' FROM '+@tbname
+N' '+@Where
EXEC sp_executesql @sql,N'@PageCount int OUTPUT',@PageCount OUTPUT
SET @PageCount=(@PageCount+@PageSize-1)/@PageSize
END
--计算分页显示的TOPN值
DECLARE @TopN varchar(20),@TopN1 varchar(20)
SELECT @TopN=@PageSize,
@TopN1=(@PageCurrent-1)*@PageSize
--第一页直接显示
IF @PageCurrent=1
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' '+@Where
+N' '+@FieldOrder)
ELSE
BEGIN
--处理别名
IF @FieldShow=N'*'
SET @FieldShow=N'a.*'
--生成主键(惟一键)处理条件
DECLARE @Where1 nvarchar(4000),@Where2 nvarchar(4000),
@s nvarchar(1000),@Field sysname
SELECT @Where1=N'',@Where2=N'',@s=@FieldKey
WHILE CHARINDEX(N',',@s)>0
SELECT @Field=LEFT(@s,CHARINDEX(N',',@s)-1),
@s=STUFF(@s,1,CHARINDEX(N',',@s),N''),
@Where1=@Where1+N' AND a.'+@Field+N'=b.'+@Field,
@Where2=@Where2+N' AND b.'+@Field+N' IS NULL',
@Where=REPLACE(@Where,@Field,N'a.'+@Field),
@FieldOrder=REPLACE(@FieldOrder,@Field,N'a.'+@Field),
@FieldShow=REPLACE(@FieldShow,@Field,N'a.'+@Field)
SELECT @Where=REPLACE(@Where,@s,N'a.'+@s),
@FieldOrder=REPLACE(@FieldOrder,@s,N'a.'+@s),
@FieldShow=REPLACE(@FieldShow,@s,N'a.'+@s),
@Where1=STUFF(@Where1+N' AND a.'+@s+N'=b.'+@s,1,5,N''),
@Where2=CASE
WHEN @Where='' THEN N'WHERE ('
ELSE @Where+N' AND ('
END+N'b.'+@s+N' IS NULL'+@Where2+N')'
--执行查询
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' a LEFT JOIN(SELECT TOP '+@TopN1
+N' '+@FieldKey
+N' FROM '+@tbname
+N' a '+@Where
+N' '+@FieldOrder
+N')b ON '+@Where1
+N' '+@Where2
+N' '+@FieldOrder)
END