sqlserver存储过程分页记录

时间:2021-10-13 08:22:07

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 ShopCode=@ShopID
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)+@ShopID+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 ('+@sql+') AS b ORDER BY b.PayAmount DESC) AS c) '
END
DECLARE @pageSql NVARCHAR(1500)
SET @pageSql = 'SELECT TOP '+STR(@pageSize)+' a.*,0 Commission FROM ('+@sql+') AS a '+ @pgSql +' ORDER BY a.PayAmount DESC'

--PRINT @pageSql
EXECUTE(@pageSql)

declare @sqlRecordCount nvarchar(1000) --得到总记录条数的语句
set @sqlRecordCount=N'select @recordCount=count(1) from ('+@sql+') 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
---------------------