我有以下存储过程,我正在处理。我注意到,每刷新一次我的第5或第6次结果,就会有新值。考虑到数据处于静态环境中并且此时没有人对数据进行任何更改,我实在无法理解。有人可以告诉我为什么我会看到不同的结果,即使我使用完全相同的参数运行此过程。我甚至在查询分析器中尝试过,仍然看到同样奇怪的结果。
我在Sql 2008中运行。
这是proc:
ALTER PROCEDURE [dbo].[SelectSearchBy_Category]
@userId INT,
@page INT,
@results INT,
@category NVARCHAR(50),
@searchTerm NVARCHAR(200) = NULL
AS
BEGIN
SET NOCOUNT ON
SET ROWCOUNT @results
DECLARE @categoryId INT
IF (@category IS NOT NULL) BEGIN
SET @categoryId = ( SELECT categoryId FROM Category WHERE categoryDescription = @category )
END
DECLARE @rowEnd INT
DECLARE @rowStart INT
SET @rowEnd = (@page * @results)
SET @rowStart = @rowEnd - @results
;WITH OrderedItems AS
(
SELECT
i.itemId,
title,
i.[description],
i.url,
i.categoryId,
i.ratingId,
i.requirements,
ISNULL(i.rating, 0) AS tating,
ISNULL(i.raters, 0) AS raters,
i.urlFriendlyPath,
ROW_NUMBER() OVER
(
ORDER BY i.dateAdded, (ISNULL(i.rating, 0) * ISNULL(i.raters, 0))
) AS RowNumber
FROM
[dbo].[Item] i
LEFT JOIN
UserItemIgnore uii ON uii.itemId = i.itemId AND uii.userId = @userId
INNER JOIN
ItemLanguage il ON il.itemId = i.itemId
WHERE
(@searchTerm IS NULL OR a.title LIKE '%' + @searchTerm + '%') AND
i.categoryId = @categoryId AND
il.languageId = 1 AND
uii.itemId IS NULL
)
SELECT *
FROM OrderedItems
WHERE RowNumber BETWEEN @rowStart AND @rowEnd
END
答案 0 :(得分:2)
如果在order by
临时表定义中放置OrderedItems
子句,则可能会得到一致的结果。
答案 1 :(得分:1)
尝试使用
ROW_NUMBER() OVER (ORDER BY i.dateAdded,
(ISNULL(i.rating, 0) * ISNULL(i.raters, 0)),
i.itemId)
i.itemId
将起到打破平局的作用,以确保ROW_NUMBER
具有相同排名的行,i.dateAdded, (ISNULL(i.rating, 0) * ISNULL(i.raters, 0))
的结果是确定性的