我在存储过程中执行以下正常查询
Select DISTINCT UI.UserId,UI.UserName, UI.FullName
From UserInfo as UI ,UserGroupRelation as UGR
Where UI.UserId = UGR.UserId AND UGR.GroupId = @pGroupId AND UI.Type = @pType
Order by UI.UserId ASC
并在存储过程中定义这些变量
@pGroupId smallint,
@pType tinyint,
@pStartIndex smallint,
@pPageSize smallint
现在,在我将此查询转换为启用分页的查询后,我编写了以下查询
SELECT UserTable.UserId,
UserTable.UserName,
UserTable.FullName
From(
Select ROW_NUMBER() OVER (
ORDER BY UI.UserId,
UI.UserName,
UI.FullName ) as [Row_Number],
UI.UserId,
UI.UserName,
UI.FullName
From UserInfo as UI,UserGroupRelation as UGR
Where UI.UserId = UGR.UserId AND UGR.GroupId = @pGroupId AND UI.Type = @pType
ORDER BY UI.UserId ASC ) as UserTable
where UserTable.[Row_Number] BETWEEN @pStartIndex AND @pStartIndex + @pPageSize
ORDER BY UserTable.[Row_Number]
但是 SQL Server 返回错误:
ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP 或 FOR XML。
还有其他选择吗?或者这个查询有什么问题。
当我像这样在子查询中添加 Top 语句时,它现在正在运行
SELECT UserTable.UserId,
UserTable.UserName,
UserTable.FullName
From(
Select Top(@pPageSize) ROW_NUMBER() OVER (
ORDER BY UI.UserId,
UI.UserName,
UI.FullName ) as [Row_Number],
UI.UserId,
UI.UserName,
UI.FullName
From UserInfo as UI,UserGroupRelation as UGR
Where UI.UserId = UGR.UserId AND UGR.GroupId = @pGroupId AND UI.Type = @pType
ORDER BY UI.UserId ASC ) as UserTable
where UserTable.[Row_Number] BETWEEN @pStartIndex AND @pStartIndex + @pPageSize
ORDER BY UserTable.[Row_Number]
但我不认为这是有效的方法。还有其他有效的方法吗?
最后我发现以下查询是最终且高效的查询
SELECT UserTable.UserId,
UserTable.UserName,
UserTable.FullName
From(
Select ROW_NUMBER() OVER (
ORDER BY UI.UserId,
UI.UserName,
UI.FullName ) as [Row_Number],
UI.UserId,
UI.UserName,
UI.FullName
From UserInfo as UI,UserGroupRelation as UGR
Where UI.UserId = UGR.UserId AND UGR.GroupId = @pGroupId AND UI.Type = @pType ) as UserTable
where UserTable.[Row_Number] BETWEEN @pStartIndex AND @pStartIndex + @pPageSize -1
ORDER BY UserTable.[Row_Number]