A CTE is basically a disposable view. It only persists for a single statement, and then automatically disappears.
Your options include:
-
Redefine the
CTEa second time. This is as simple as copy-paste fromWITH...through the end of the definition to before yourSET. -
Put your results into a
#temptable or a@tablevariable -
Materialize the results into a real table and reference that
-
Alter slightly to just
SELECT COUNTfrom 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