我有下面的存储过程,它在不返回总记录的情况下工作得很好,但是当我在单独的查询中返回总记录时,它变得很慢。
有没有另一种方法可以更快地返回总记录
视图是
SELECT dbo.tbl_ImagesMaster.ImgTitle, dbo.tbl_ImagesMaster.ImgID, dbo.tbl_ImagesMaster.ImgDate, dbo.tbl_ImagesMaster.ImgActive,
dbo.tbl_ImagesMaster.ImgHits, dbo.aspnet_Users.UserName, dbo.tbl_ImagesMaster.ImgUserID, dbo.tbl_ImagesDetails.ImgDPath,
dbo.tblUsersExtended.UAvatar, dbo.tbl_ImagesMaster.ImgRemarks
FROM dbo.tbl_ImagesMaster INNER JOIN
dbo.aspnet_Users ON dbo.tbl_ImagesMaster.ImgUserID = dbo.aspnet_Users.UserId INNER JOIN
dbo.tbl_ImagesDetails ON dbo.tbl_ImagesMaster.ImgID = dbo.tbl_ImagesDetails.ImgDParentID INNER JOIN
dbo.tblUsersExtended ON dbo.aspnet_Users.UserId = dbo.tblUsersExtended.UUserID
WHERE (dbo.tbl_ImagesDetails.ImgDDefault = 1)
SP
ALTER Procedure [dbo].[usp_searchImagestest]
(
@CurrentPage As int=1,
@PageSize As int=10,
@searchType As int=1,
@Activeflag As bit=null,
@searchTerm as nvarchar(200),
@TotalRecords As int OUTPUT
)
As
begin
-- Turn off count return.
Set NoCount On
--Full text search
if @searchType=1
begin
select
ImgID,ImgTitle,ImgDate,imgHits,UserName,uavatar,RowRank
from
(Select
ImgID,imgtitle,ImgDate,imghits,UserName,UAvatar
, ROW_NUMBER() OVER (ORDER BY ImgID desc) AS RowRank
From
vw_MasterImagesSearch
WHERE FREETEXT(*, @searchTerm) and (@Activeflag IS NULL or ImgActive=@Activeflag)
) as MyImages
where
RowRank > (@PageSize * (@CurrentPage-1)) AND RowRank <= (@CurrentPage * @PageSize)
-- TOTAL RECORD, WHICH SLOW DOWN THE WHOLE SP EXECUTION
select @TotalRecords = (select COUNT(*) From vw_MasterImagesSearch
WHERE FREETEXT(*, @searchTerm) and (@Activeflag IS NULL or ImgActive=@Activeflag))
end
编辑
我试过这个
查询 1
select
ImgID,ImgTitle,ImgDate,imgHits,RowRank,TOTALCOUNT,
(select username from aspnet_Users where UserId=MyImages.imguserid) as username,
(select UAvatar from tblUsersExtended where UUserID=MyImages.imguserid) as Uavatar
from
(Select
ImgID,imgtitle,ImgDate,imghits,ImgUserID
, ROW_NUMBER() OVER (ORDER BY ImgID desc) AS RowRank
,COUNT(*) OVER() AS TOTALCOUNT
From
tbl_ImagesMaster
WHERE FREETEXT(ImgTitle, @searchTerm) and (@Activeflag IS NULL or ImgActive=@Activeflag)
) as MyImages
where
RowRank > (@PageSize * (@CurrentPage-1)) AND RowRank <= (@CurrentPage * @PageSize)
查询 2
select
ImgID,ImgTitle,ImgDate,imgHits,RowRank,
(select username from aspnet_Users where UserId=MyImages.imguserid) as username,
(select UAvatar from tblUsersExtended where UUserID=MyImages.imguserid) as Uavatar
from
(Select
ImgID,imgtitle,ImgDate,imghits,ImgUserID
, ROW_NUMBER() OVER (ORDER BY ImgID desc) AS RowRank
From
tbl_ImagesMaster
WHERE FREETEXT(ImgTitle, @searchTerm) and (@Activeflag IS NULL or ImgActive=@Activeflag)
) as MyImages
where
RowRank > (@PageSize * (@CurrentPage-1)) AND RowRank <= (@CurrentPage * @PageSize)
select @TotalRecords = (select COUNT(*) From tbl_ImagesMaster
WHERE FREETEXT(ImgTitle, @searchTerm) and (@Activeflag IS NULL or ImgActive=@Activeflag))
查询 1 用时 3 秒 查询 2 用时不到 1 秒
表中的总行数为 100,000 行