admin

多次使用一个CTE

sql

我有这个,在设定的总数时我得到一个错误。为什么我不能多次访问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 )

阅读 186

收藏
2021-05-10

共1个答案

admin

ACTE基本上是一次性视图。它只保留一个语句,然后自动消失。

您的选择包括:

  • 重新定义CTE第二次。从WITH...定义的末尾到您的之前,这就像复制粘贴一样简单SET

  • 将结果放入#temp表格或@table变量中

  • 将结果具体化为真实表并引用

  • 稍微更改一下即可,只需SELECT COUNT从您的CTE:

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
2021-05-10