sqlserver 存储过程分页
Posted wangdrama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver 存储过程分页相关的知识,希望对你有一定的参考价值。
USE [HK_ERP_Report] GO /****** Object: StoredProcedure [dbo].[spPF_AppRpt_Tupu_CommonPage] Script Date: 2019/4/4 12:00:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* DECLARE @return_value int, @PageCount int, @TotalRecord int EXEC @return_value = [dbo].[spPF_AppRpt_Tupu_CommonPage] @TableName = N‘PF_Shopper‘, @ReFieldsStr = N‘*‘, @OrderString = N‘LastVisitTime asc‘, @PageSize = 10, @PageIndex = 1, @TotalRecord = @TotalRecord OUTPUT, @PageCount = @PageCount OUTPUT SELECT @TotalRecord as N‘@TotalRecord‘,@PageCount as N‘@PageCount‘ SELECT ‘Return Value‘ = @return_value */ ALTER PROCEDURE [dbo].[spPF_AppRpt_Tupu_CommonPage] @TableName VARCHAR(50), --表名 @ReFieldsStr VARCHAR(200) = ‘*‘, --字段名(全部字段为*) @OrderString VARCHAR(200), --排序字段(必须!支持多字段不用加order by) @WhereString VARCHAR(500) =N‘‘, --条件语句(不用加where) @PageSize INT = 10, --每页多少条记录 @PageIndex INT = 1 , --指定当前为第几页 @PageCount INT = 0 OUTPUT , --总页数 @TotalRecord INT OUTPUT --返回总记录数 AS BEGIN --处理开始点和结束点 DECLARE @StartRecord INT; DECLARE @EndRecord INT; DECLARE @TotalCountSql NVARCHAR(500); DECLARE @SqlString NVARCHAR(2000); SET @StartRecord = (@PageIndex-1)*@PageSize + 1--起始记录 SET @EndRecord = @StartRecord + @PageSize - 1 --结尾记录 SET @TotalCountSql= N‘select @TotalRecord = count(*) from ‘ + @TableName;--总记录数语句 SET @SqlString = N‘(select row_number() over (order by ‘+ @OrderString +‘) as rowId,‘[email protected]+‘ from ‘+ @TableName;--查询语句 -- IF (@WhereString! = ‘‘ or @WhereString!=null) BEGIN SET @[email protected] + ‘ where ‘+ @WhereString; SET @SqlString [email protected]+ ‘ where ‘+ @WhereString; END --第一次执行得到 EXEC sp_executesql @totalCountSql,N‘@TotalRecord int out‘,@TotalRecord OUTPUT;--返回总记录数 SET @[email protected]/@pageSize+(CASE WHEN @TotalRecord%@pageSize>0 THEN 1 ELSE 0 END) ----执行主语句 SET @SqlString =‘select * from ‘ + @SqlString + ‘) as t where rowId between ‘ + ltrim(str(@StartRecord)) + ‘ and ‘ + ltrim(str(@EndRecord)); Exec(@SqlString) END
以上是关于sqlserver 存储过程分页的主要内容,如果未能解决你的问题,请参考以下文章