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
---------------------
sqlserver存儲過程分頁記錄