I have a question that arises when I used the WITH clause in one of my script. The question is easy to indicate that I want to use the CTE alias several times, and not just in the external request, and there is a difficult question.
For instance:
-- Define the CTE expression WITH cte_test (domain1, domain2, [...]) AS -- CTE query ( SELECT domain1, domain2, [...] FROM table ) -- Outer query SELECT * FROM cte_test -- Now I wanna use the CTE expression another time INSERT INTO sometable ([...]) SELECT [...] FROM cte_test
The last line will result in the following error, since it is outside the external query:
Msg 208, Level 16, State 1, Line 12 Invalid object name 'cte_test'.
Is there a way to use CTE several times or. make it persistent? My current solution is to create a temporary table in which I store the result of the CTE and use this temporary table for any further statements.
-- CTE [...] -- Create a temp table after the CTE block DECLARE @tmp TABLE (domain1 DATATYPE, domain2 DATATYPE, [...]) INSERT INTO @tmp (domain1, domain2, [...]) SELECT domain1, domain2, [...] FROM cte_test -- Any further DML statements SELECT * FROM @tmp INSERT INTO sometable ([...]) SELECT [...] FROM @tmp [...]
Honestly, I do not like this solution. Does anyone else have best practice for this problem?
Thanks in advance!
source share