Use one CTE many times

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

    A CTE is basically a disposable view. It only persists for a single statement, and then automatically disappears.

    Your options include:

    • Redefine the CTE a second time. This is as simple as copy-paste from WITH... through the end of the definition to before your SET.

    • Put your results into a #temp table or a @table variable

    • Materialize the results into a real table and reference that

    • Alter slightly to just SELECT COUNT from your 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
    

提交回复
热议问题