Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one CTE many times

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,     @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 ) SELECT Id, Name FROM CTEPlayers c WHERE RowNumber>@pageSize*(@pageNumber-1) AND RowNumber<@pageSize*@pageNumber; SET @total = ( SELECT COUNT(*) FROM CTEPlayers ) 
like image 433
gigi Avatar asked Apr 17 '12 18:04

gigi


People also ask

Can we use same CTE multiple times?

Unlike a derived table, a CTE behaves more like an in-line view and can be referenced multiple times in the same query. Using a CTE makes complex queries easier to read and maintain. Because a CTE can be referred to multiple times in a query, syntax can be simpler.

How many times can you use a CTE?

The CTE runs only once. The Nested Loops operator splits every row into four. And the statistics add up: The original query performed around 82,000 logical reads on dbo. Posts and 178,000 logical reads on dbo.

How do I use the same CTE for multiple queries?

You can't use CTE with multiple queries. Use of CTE or you can say its scope is restricted to its query only. For using in other queries you have to create the same CTE again. To use the same logic again, you can create a VIEW of the CTE and use it again.

Can you reuse a CTE?

YES you can reuse it!


1 Answers

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 
like image 149
JNK Avatar answered Sep 29 '22 04:09

JNK