我有这张桌子
CREATE TABLE [dbo].[friend_blocked_list](
[subdomain] [varchar](50) NOT NULL,
[un] [nvarchar](50) NOT NULL,
[friend] [nvarchar](50) NOT NULL,
[is_blocked] [bit] NOT NULL,
[approved] [bit] NOT NULL)
我使用以下查询从中选择数据。选择查询将添加用户为好友的用户和已添加为好友的用户按用户组合
declare @un varchar(50), @subdomain varchar(50)
set @un='user2';
set @subdomain ='test.domain.com';
WITH FRIENDS as
(
SELECT friend
FROM friend_blocked_list
WHERE un=@un and subdomain=@subdomain and approved=1 and is_blocked=0
UNION ALL
SELECT un as friend
FROM friend_blocked_list
WHERE friend=@un and subdomain=@subdomain and approved=1 and is_blocked=0
)
select friend from FRIENDS group by FRIENDS.friend order by FRIENDS.friend asc
它适用于少量数据,但我希望能够在服务器端进行分页以减少负载。我正在尝试将它与下面的分页 sp
create PROCEDURE [dbo].[Paging]
@subdomain varchar(50),
@un varchar(50),
@PageNumber int,
@PageSize int
AS
BEGIN
--paging
DECLARE @FirstRow INT,@LastRow INT,@RowCount INT,@PageCount INT
--find recordcount and pages
SELECT @RowCount = COUNT(*), @PageCount = COUNT(*) / @PageSize
FROM friend_blocked_list
WHERE subdomain=@subdomain AND un=@un AND approved=1 AND is_blocked=0;
--- calculate pages
IF @RowCount % @PageSize != 0 SET @PageCount = @PageCount + 1
IF @PageNumber < 1 SET @PageNumber = 1
IF @PageNumber > @PageCount SET @PageNumber = @PageCount
SELECT
CurrentPage = @PageNumber,
TotalPages = @PageCount,
TotalRows = @RowCount
-- mora calculation
SELECT @FirstRow = ( @PageNumber - 1) * @PageSize + 1,
@LastRow = (@PageNumber - 1) * @PageSize + @PageSize ;
WITH MyTopics AS
(
SELECT *, ROW_NUMBER() OVER (order by un asc) AS RowNumber
FROM friend_blocked_list
WHERE subdomain=@subdomain AND un=@un AND approved=1 AND is_blocked=0
)
SELECT *
FROM MyTopics
WHERE RowNumber BETWEEN @FirstRow AND @LastRow
ORDER BY RowNumber ASC;
end
但和往常一样,我遇到了麻烦:)。主要问题是UNION ALL
在我的查询中。它阻止我使用ROW_NUMBER() OVER
.
有任何想法吗?