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 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
---------------------

转载于:https://www.cnblogs.com/wangdrama/p/9876665.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值