Use one CTE many times

后端 未结 6 1955
鱼传尺愫
鱼传尺愫 2020-12-13 17:16

I have this, and i get an error at set total. Why can\'t i access a cte many times?

ALTER PROCEDURE [dbo].[GetLeaguePlayers]
(
    @idleague int,
    @pageNu         


        
6条回答
  •  囚心锁ツ
    2020-12-13 17:36

    None of the above answers are correct... You can execute CTE once and achieve the result you want.. here is the query

    ALTER PROCEDURE [dbo].[GetLeaguePlayers]
    (
        @idleague int,
        @pageNumber int,
        @pageSize int,
        @total int OUTPUT
    )
    AS
    WITH CTEPlayers AS
    (
        SELECT 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
    ),
    TotalCount AS
    (
     SELECT COUNT(*) AS Total FROM CTEPlayers
    ),
    Final_Result AS
    (
     SELECT ROW_NUMBER() OVER (ORDER BY p.Name) AS RowNumber, p.Id, p.Name, t.Name AS Team,
      (SELECT Total FROM TotalCount) AS Total
        FROM CTEPlayers
    )
    SELECT Id, Name, @total = Total
    FROM Final_Results c
    WHERE RowNumber>@pageSize*(@pageNumber-1) AND RowNumber<@pageSize*@pageNumber;
    

提交回复
热议问题