我在SQL Server 2008 R2中使用此存储过程进行分页:
ALTER PROCEDURE [SelectPaging]
@SelectedColumn nvarchar(max),
@ViewName nvarchar(200),
@PrimaryKeyName nvarchar(100),
@RowCountOnPage int,
@PageNumberDesired int,
@Condition nvarchar(max),
@OrderBy nvarchar(200),
@OrderByAsc bit,
@UserID int,
@ErrorNumber int out,
@TotalRowsCount int out
as
begin
SET NOCOUNT ON;
Begin Try
exec [general].TotalRowsWithFiltering @PrimaryKeyName,@viewName ,@Condition ,@UserID,@TotalRowsCount out,@ErrorNumber out
declare @RowNumberFrom int,@RowNumberTo int
set @RowNumberFrom=((@PageNumberDesired-1)*@RowCountOnPage)
set @RowNumberTo=(@PageNumberDesired*@RowCountOnPage)+1
if @Condition='' or @Condition is null
set @Condition=' 1=1 '
else set @Condition=@Condition
if @OrderBy='' or @OrderBy is null
set @OrderBy=@PrimaryKeyName
declare @OrderByAsc_Desc nvarchar(6)
if (@OrderByAsc='false' or @OrderByAsc is null)
set @OrderByAsc_Desc=' Desc'
else if @OrderByAsc='true'
set @OrderByAsc_Desc=' Asc'
declare @SQLQuery nvarchar(max)
set @SQLQuery='SELECT
*
FROM (
SELECT
*,
ROW_NUMBER() OVER (order by '+@OrderBy+' '+@OrderByAsc_Desc+') AS RowNumber
FROM (
SELECT '+@SelectedColumn+'
FROM '+@viewName+' where ' + @Condition +'
) AS d
) AS c
where RowNumber >'+cast(@RowNumberFrom as nvarchar(10))+' and RowNumber < '+cast(@RowNumberTo as nvarchar(10))
EXECUTE sp_executesql @SQLQuery
set @ErrorNumber=@@ERROR
END TRY
BEGIN CATCH
END CATCH
end
我在具有700.000条记录的视图上运行查询。 当我在视图上选择查询时,运行时为零。 但是,当我运行此sp进行分页时,需要50-60秒的时间才能为每页提取10条记录
如何优化?
答案 0 :(得分:0)
您可以使用此代码进行分页。...支持SQL Server 2012+版本的OFFSET。因此,请先升级服务器版本。然后在表中创建索引以快速搜索
declare @Page bigint=1,@pageSize bigint = 20
SELECT * FROM AC_TRN_STOCKHEADER
Order by HEADER_ID desc
OFFSET (@Page-1) ROWS
FETCH NEXT @pageSize ROWS ONLY
-----==================================
-----Code to Create an index
CREATE NONCLUSTERED INDEX IDX_HEADER_ID ON YOUR_TABLE_NAME (KEY_FIELD_OF_TABLE)
ON THE ABOVE CODE "AC_TRN_STOCKHEADER" is my Table Name and "Header_ID" is my Key_FIELD
Hence,
CREATE NONCLUSTERED INDEX IDX_HEADER_ID ON AC_TRN_STOCKHEADER (Header_ID)
希望它可以解决您的问题。