在存储过程中将简单T-SQL查询转换为支持分页的查询

在存储过程中将简单T-SQL查询转换为支持分页的查询,sql,sql-server,tsql,stored-procedures,paging,Sql,Sql Server,Tsql,Stored Procedures,Paging,我的存储过程中有以下正常查询 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 并在存储过程中定义这些变量 @

我的存储过程中有以下正常查询

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返回错误时说:

除非还指定了TOP或FOR XML,否则ORDER BY子句在视图、内联函数、派生表、子查询和公共表表达式中无效

是否有其他选择或此查询有什么问题

现在,当我在子查询中添加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]

现在在SQL Server 2012中,我们内置了一个子句来执行分页,我们不需要编写这么大的查询来实现分页:)