Use one CTE many times

后端 未结 6 1981
鱼传尺愫
鱼传尺愫 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:39

    Store the output in temporary table along-with the total count; set the output variable value and return the required columns from temporary table

    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
    ),
    TotalCounter(TotalRecords) as
    (select count(1) from CTEPlayers)
    
    
    SELECT Id, Name, TotalRecords(select TotalRecords from TotalCounter) into #tmp
    FROM CTEPlayers c
    WHERE RowNumber>@pageSize*(@pageNumber-1) AND RowNumber<@pageSize*@pageNumber;
    
    SET @total = ( SELECT TotalRecords FROM #tmp)
    
    select Id, Name from $tmp
    
    drop table #tmp
    

提交回复
热议问题