Avatar of Éric Moreau
Éric Moreau
Flag for Canada asked on

CTE - cannot query the results twice

Here is a very simple CTE:

;
WITH test
AS
(
       SELECT GETDATE() AS CurrentDate
)

SELECT * FROM test
SELECT * FROM test

Open in new window


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

Avatar of undefined
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.
ASKER CERTIFIED SOLUTION
Aneesh

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Aneesh

CTE was created as a destroyable view which persists for a single statement, and then automatically disappears.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Jim Horn

>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.
Éric Moreau

ASKER
Thanks
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.