MS SQL 分页存储过程
Posted witeem
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MS SQL 分页存储过程相关的知识,希望对你有一定的参考价值。
最近换了家新公司,但是新公司没有使用分页的存储过程。哎~~,硬着头皮自己尝试写了一个,别说还挺好用的。(效率怎么样就不怎么清除没有详细的测试过)
CREATE PROCEDURE [dbo].[pro_common_pageList] ( @tab NVARCHAR(MAX) ,---表名 @PrimaryKey VARCHAR(100) , --主键ID @strFld NVARCHAR(MAX) , --字段字符串 @strWhere NVARCHAR(MAX) = ‘ ‘ , --where条件 @IsDistinct BIT , @PageIndex INT , --页码 @PageSize INT , --每页容纳的记录数 @Order VARCHAR(255) = ‘ ‘ , --排序字段及规则,不用加order by @Sort VARCHAR(20) = ‘desc‘ , @TotalCount INT OUTPUT --总记录数 ) AS BEGIN SET NOCOUNT ON; DECLARE @strSql VARCHAR(MAX); IF @strFld IS NULL OR @strFld = ‘ ‘ BEGIN SET @strFld = ‘*‘; END; IF @Order IS NULL OR @Order = ‘ ‘ BEGIN SET @Order = @PrimaryKey; END; --计算总记录数 DECLARE @sqlRecordCount NVARCHAR(MAX); --得到总记录条数的语句 DECLARE @recordCount INT; --保存总记录条数的变量 DECLARE @distinct NVARCHAR(20)= ‘ ‘; IF @IsDistinct = 1 BEGIN SET @distinct = ‘ DISTINCT ‘; END; SET @sqlRecordCount = N‘SELECT @recordCount=COUNT(1) FROM (SELECT ‘ + @distinct + ‘ ‘ + @strFld + ‘ FROM ‘ + @tab + ‘ WHERE 1=1 ‘ + @strWhere + ‘ ) AS TEMPTABLE‘; EXEC sp_executesql @sqlRecordCount, N‘@recordCount int output‘, @recordCount OUTPUT; SET @TotalCount = @recordCount; --数据查询 --当@PageIndex=1,使用TOP效率较快 IF @PageIndex = 1 BEGIN SET @strSql = ‘SELECT ‘ + @distinct + ‘ TOP ‘ + STR(@PageSize) + ‘ ‘ + @strFld + ‘,0 AS rownum FROM ‘ + @tab + ‘ WHERE 1=1 ‘ + @strWhere + ‘ ORDER BY ‘ + @Order + ‘ ‘ + @Sort; END; ELSE BEGIN SET @strSql = ‘SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY ‘ + @PrimaryKey + ‘) AS rownum FROM ‘; --是否去重:1去重 IF @IsDistinct = 1 BEGIN SET @strSql = @strSql + ‘ (SELECT DISTINCT ‘ + @strFld + ‘ FROM ‘ + @tab + ‘ WHERE 1=1 ‘ + @strWhere + ‘ ) AS S ‘; END; ELSE BEGIN SET @strSql = @strSql + ‘ ‘ + @tab + ‘ WHERE 1=1 ‘ + @strWhere; END; SET @strSql = @strSql + ‘) AS Dwhere WHERE Dwhere.rownum BETWEEN ‘ + CAST(( ( @PageIndex - 1 ) * @PageSize ) + 1 AS NVARCHAR(20)); SET @strSql = @strSql + ‘ AND ‘ + CAST(( @PageIndex * @PageSize ) AS NVARCHAR(20)); SET @strSql = @strSql + ‘ ORDER BY ‘ + @Order + ‘ ‘ + @Sort; END; PRINT(@strSql) EXEC (@strSql); SET NOCOUNT OFF; END;
以上是关于MS SQL 分页存储过程的主要内容,如果未能解决你的问题,请参考以下文章
在执行读取/更新的 MS SQL 存储过程上获取死锁(放置代码来处理死锁)