我想在存储过程中添加一个列,该列只是从1开始计数,而不管数据的排序方式或我正在获取的页面(使用偏移量。)
存储过程本身如下所示:
SELECT
e.EntityId, e.HierarchyId, e.ParentNode, e.NgageId, e.NgageParentId,
e.Type, e.IsDeleted, e.LastIndexedDate, e.CurrentVersion, e.Level,
v.EntityVersionID, v.VerisonNotes, v.Title, v.[Description], v.FormID,
v.IsPublic, v.CreatedDate, v.LastModifiedDate, v.ExpirationDate,
d.DocumentID, d.OwnerId AS OwnerId,
o.ADUsername AS OwnerAccount, o.Name AS Author,
d.[Status], d.DocumentType, d.CheckoutUserId AS CheckoutUserId,
c.ADUsername AS CheckoutUserAccount, c.Name AS CheckoutUserName,
d.CheckoutDate,
dbo.GetCommaSeperatedTags(e.EntityID) AS Tags
--INTO #documentsTemp
FROM
dbo.Entities AS e
INNER JOIN
dbo.EntityVersions AS v ON v.EntityID = e.EntityID AND e.CurrentVersion = v.VersionNumber
INNER JOIN
dbo.Documents AS d ON d.EntityVersionID = v.EntityVersionID
INNER JOIN
dbo.Users AS o ON o.UserID = d.OwnerId
LEFT JOIN
dbo.Users AS c ON c.UserID = d.CheckoutUserId
WHERE
[Type] = 5
AND NgageID = @ngageId
AND IsDeleted = 0
AND dbo.CheckPermissions(e.EntityId, @userId, 'LIST') = 1
ORDER BY
CASE WHEN @orderBy = 'Title' THEN v.Title END,
CASE WHEN @orderBy = 'Title' AND @desc = 1 THEN v.Title END DESC,
CASE WHEN @orderBy = 'Author' THEN o.Name END,
CASE WHEN @orderBy = 'Author' AND @desc = 1 THEN o.Name END DESC,
CASE WHEN @orderBy = 'DateModified' THEN v.LastModifiedDate END,
CASE WHEN @orderBy = 'DateModified' AND @desc = 1 THEN v.LastModifiedDate END DESC
OFFSET ((@pageNumber - 1) * @pageSize) ROWS
FETCH NEXT @pageSize ROWS ONLY;
这样做的最佳方式是什么?
谢谢,
乔
答案 0 :(得分:0)
我看到三个选项(Gordon已经提到过两个选项,不建议使用第三个选项):
以下是AdventureWorks中的选项2和3(缩短查询):
DECLARE @pageSize int=5, @pagenumber int=2, @OrderBy varchar(20)='Name'
SELECT (ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @OrderBy='Name' THEN Name END,
CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
)-1)%@pageSize+1 as N, *
FROM Production.Product
ORDER BY
CASE WHEN @OrderBy='Name' THEN Name END,
CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
OFFSET ((@pageNumber - 1) * @pageSize) ROWS
FETCH NEXT @pageSize ROWS ONLY
SELECT ROW_NUMBER() OVER (ORDER BY @pageSize) AS RN, *
FROM (
SELECT * FROM Production.Product
ORDER BY
CASE WHEN @OrderBy='Name' THEN Name END,
CASE WHEN @OrderBy='ProductNumber' THEN ProductNumber END
OFFSET ((@pageNumber - 1) * @pageSize) ROWS
FETCH NEXT @pageSize ROWS ONLY
) X
勒兹