Skip to content
Advertisement

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?

Advertisement

Answer

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:

.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement