我有下面的 SQL 存储过程:
ALTER PROCEDURE [dbo].[sp_getpaginatedusersbyglobalfilter]
@globalFilter varchar(max)
, @pageSize int
, @page int
, @totalRecords int output
, @totalFilteredRecords int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
;WITH PaginatedUsers AS(
SELECT ROW_NUMBER() OVER(ORDER BY u.LastName) ID
, u.Username
, u.FirstName
, u.OtherNames
, u.LastName
, e.Nombre
, r.RoleName
, u.PhoneNumber
FROM webpages_Users u
INNER JOIN Establecimiento e
ON u.FacilityId = e.IDReporte
AND e.EstadoRegistro = 1
INNER JOIN webpages_UsersInRoles ur
ON u.UserId = ur.UserId
INNER JOIN webpages_Roles r
ON ur.RoleId = r.RoleId
WHERE u.Username LIKE '%' + @globalFilter + '%'
OR u.FirstName LIKE '%' + @globalFilter + '%'
OR u.OtherNames LIKE '%' + @globalFilter + '%'
OR u.LastName LIKE '%' + @globalFilter + '%'
OR e.Nombre LIKE '%' + @globalFilter + '%'
OR r.RoleName LIKE '%' + @globalFilter + '%'
OR u.PhoneNumber LIKE '%' + @globalFilter + '%'
)
SELECT pu.ID, pu.Username
, pu.FirstName
, pu.OtherNames
, pu.LastName
, pu.Nombre AS FacilityName
, pu.RoleName
, pu.PhoneNumber
FROM PaginatedUsers pu
WHERE pu.ID BETWEEN ((@page - 1) * @pageSize + 1)
AND @page * @pageSize
SELECT @totalFilteredRecords = COUNT(pu.ID)
FROM PaginatedUsers pu
SELECT @totalRecords = COUNT(u.UserId)
FROM webpages_Users u
END
我遇到的问题是该部分:
SELECT @totalFilteredRecords = COUNT(pu.ID)
FROM PaginatedUsers pu
我得到的错误是“无效的对象名称'PaginatedUsers'”。根据我的研究,我不能在查询中多次使用 PaginatedUsers(由 WITH 产生)对象。那么,如何返回输出变量@totalFilteredRecords 中的记录总数?我一直在考虑将结果插入到临时表中,然后从中获取计数以及最终结果集,但我不喜欢这个想法。我能做些什么?
谢谢。