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 fromWITH...
through the end of the definition to before yourSET
. -
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