Why can't I select twice on the CTE table? The second select statement returns an error: (1 row(s) affected)
Msg 208, Level 16, State 1, Line 9
Invalid object name 'test'.
Microsoft SQL ServerMicrosoft SQL Server 2008SQL
Last Comment
Éric Moreau
8/22/2022 - Mon
Jim Horn
Nope. The scope of a CTE defined set exists only within the statement immediately after it.
After that, it's gone.
If you need it to live throughout a SP/whatever, then create a temporary table (#temp), insert into that temp table, and use it.
Éric Moreau
ASKER
I know it is not available after the first query. I am looking for a reference of the official reason on why it is like this.
>I am looking for a reference of the official reason on why it is like this. First paragraph...
A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
Scott Pletcher
As to "why", I think because that's what a CTE was designed and intended to be. You can already use temp or work tables if you want to query a result multiple times. In particular, CTEs were used to implement recursion, which added a great new feature to SQL Server.
After that, it's gone.
If you need it to live throughout a SP/whatever, then create a temporary table (#temp), insert into that temp table, and use it.