临时表的分页SQL

一段使用临时表的分页SQL
ALTER PROCEDURE [dbo].[usp_DC_Vendor_Report_List_Get] --存储过程名字以usp开头,后面跟着该SP的功能,不要乱起名字 @startDate DATETIME , @endDate DATETIME , @VendorNo VARCHAR(50) , @PageIndex INT , @PageSize INT , @TotalRecordCount INT OUTPUT AS BEGIN SET NOCOUNT ON DECLARE @StartIndex INT DECLARE @EndIndex INT SET @StartIndex = @PageSize * ( @PageIndex - 1 ) + 1 SET @EndIndex = @PageSize * @PageIndex --创建临时表,用户存放所有查询结果 CREATE TABLE #Temp ( ID INT IDENTITY(1, 1) PRIMARY KEY , --索引,分页时根据这个字段来取记录 StartDate DATETIME , --以下字段为输出字段,不必要的字段不要输出,影响效率 EndDate DATETIME , VendorNo VARCHAR(50) , VendorName VARCHAR(50) ) --把查询出的结果集插入临时表 INSERT INTO #Temp ( StartDate , EndDate , VendorNo , VendorName ) SELECT @startDate StartDate , @endDate EndDate , ob.VendorCode VendorNo , MAX(ob.VendorName) VendorName FROM dbo.OrderBody ob INNER JOIN dbo.OrderHeader oh ON ob.OrderHeaderNo = oh.OrderHeaderNo WHERE ob.DeliveryDate >= @startDate AND ob.DeliveryDate <= @endDate AND ( @VendorNo IS NULL OR ob.VendorCode = @VendorNo ) AND ob.DCVendor = dbo.Get_DC_VendorNo() AND ob.SubmitFlag = 1 AND ob.ActiveFlag = 1 AND oh.ActiveFlag = 1 GROUP BY ob.VendorCode --ORDER BY ob.DeliveryDate DESC --取出相应分页的结果集 SELECT StartDate , EndDate , VendorNo , VendorName FROM #Temp WHERE ID >= @StartIndex AND ID <= @EndIndex --返回总结果集的数量 SET @TotalRecordCount = ( SELECT COUNT(ID) FROM #Temp ) --删除临时表 DROP TABLE #Temp -- SELECT a.LastLoginTime StartDate , -- a.LastLoginTime EndDate , -- a.Phone VendorNo , -- a.Phone VendorName -- FROM dbo.AdminUser a SET NOCOUNT OFF END 

你可能感兴趣的:(JOIN,list,report,table,null,insert)