我有这个,在设定的总数时我得到一个错误。为什么我不能多次访问CTE?
ALTER PROCEDURE [dbo].[GetLeaguePlayers] ( @idleague int, @pageNumber int, @pageSize int, @total int OUTPUT ) AS WITH CTEPlayers AS ( SELECT ROW_NUMBER() OVER (ORDER BY p.Name) AS RowNumber, p.Id, p.Name, t.Name AS Team FROM Players p INNER JOIN Teams t ON p.IdTeam=t.Id INNER JOIN Leagues l ON l.Id=t.IdLeague WHERE l.Id=@idleague ) SELECT Id, Name FROM CTEPlayers c WHERE RowNumber>@pageSize*(@pageNumber-1) AND RowNumber<@pageSize*@pageNumber; SET @total = ( SELECT COUNT(*) FROM CTEPlayers )
ACTE基本上是一次性视图。它只保留一个语句,然后自动消失。
CTE
您的选择包括:
重新定义CTE第二次。从WITH...定义的末尾到您的之前,这就像复制粘贴一样简单SET。
WITH...
SET
将结果放入#temp表格或@table变量中
#temp
@table
将结果具体化为真实表并引用
稍微更改一下即可,只需SELECT COUNT从您的CTE:
SELECT COUNT
。
SELECT @total = COUNT(*) FROM Players p INNER JOIN Teams t ON p.IdTeam=t.Id INNER JOIN Leagues l ON l.Id=t.IdLeague WHERE l.Id=@idleague