sqlserver存储过程分页记录

Posted wangdrama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver存储过程分页记录相关的知识,希望对你有一定的参考价值。

USE [HK_ERP]
GO
/****** Object: StoredProcedure [dbo].[GetPageBillsByShopID] Script Date: 2018/10/30 11:11:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[GetPageUserBillsByShopID]
(
@ShopID VARCHAR(50),--店铺id
@BeginDate DATETIME,
@EndDate DATETIME,
@pageIndex int,--页索引
@pageSize int,--每页显示数
@pageCount int output,--总页数,输出参数
@totalCount int output--总条数
)
as
begin
set nocount on;
SELECT TOP 1 @ShopID = ShopID FROM dbo.Bas_Shop WHERE [email protected]
SET @BeginDate=ISNULL(@BeginDate,‘1970-01-01‘);
SET @EndDate=ISNULL(@EndDate,GETDATE());
declare @sql nvarchar(1000)
SET @sql = ‘SELECT SaleID as EmployeeCode,SUM(b.PayAmount) AS PayAmount,COUNT(1) AS BillCount FROM BC_Sal_OrderMaster b WHERE b.ShopID=‘+char(39)[email protected]+char(39)+‘ AND SaleID is not null AND SaleID !=‘+char(39)+char(39)+‘ AND BillDate >=‘+CHAR(39)+CONVERT(VARCHAR(50),@BeginDate)+CHAR(39)+‘ AND BillDate <=‘+CHAR(39)+CONVERT(VARCHAR(50),@EndDate)+CHAR(39)+‘ GROUP BY SaleID‘

DECLARE @pgSql NVARCHAR(2000)=‘‘
IF @pageIndex >1
BEGIN
SET @pgSql = ‘WHERE a.PayAmount < (SELECT MIN(c.PayAmount) from (SELECT TOP ‘+STR((@pageIndex-1)*@pageSize)+‘ * FROM (‘[email protected]+‘) AS b ORDER BY b.PayAmount DESC) AS c) ‘
END
DECLARE @pageSql NVARCHAR(1500)
SET @pageSql = ‘SELECT TOP ‘+STR(@pageSize)+‘ a.*,0 Commission FROM (‘[email protected]+‘) AS a ‘+ @pgSql +‘ ORDER BY a.PayAmount DESC‘

--PRINT @pageSql
EXECUTE(@pageSql)

declare @sqlRecordCount nvarchar(1000) --得到总记录条数的语句
set @sqlRecordCount=N‘select @recordCount=count(1) from (‘[email protected]+‘) as r‘
declare @recordCount int --保存总记录条数的变量SELECT
exec sp_executesql @sqlRecordCount,N‘@recordCount int output‘,@recordCount output

if( @recordCount % @pageSize = 0) --如果总记录条数可以被页大小整除
set @pageCount = @recordCount / @pageSize --总页数就等于总记录条数除以页大小
else --如果总记录条数不能被页大小整除
set @pageCount = @recordCount / @pageSize + 1 --总页数就等于总记录条数除以页大小加1

set @totalCount = @recordCount

set nocount off;
end
---------------------








































以上是关于sqlserver存储过程分页记录的主要内容,如果未能解决你的问题,请参考以下文章

ADO调用分页查询存储过程

存储过程sql server中的分页

数据库sqlserver如何用存储过程做分页

SQLServer分页查询存储过程

SQLServer 存储过程实现单条件分页

原创10万条数据采用存储过程分页实现(Mvc+Dapper+存储过程)