Jak Mogę mieć wiele wspólnych wyrażeń tabel w jednej instrukcji SELECT?

Jestem w trakcie upraszczania skomplikowanej instrukcji select, więc pomyślałem, że użyję wspólnych wyrażeń tabel.

Deklarowanie pojedynczego cte działa dobrze.
WITH cte1 AS (
    SELECT * from cdr.Location
    )

select * from cte1 

Czy Można zadeklarować i użyć więcej niż jednego cte w tym samym SELECT?

Ie ten sql daje błąd

WITH cte1 as (
    SELECT * from cdr.Location
)

WITH cte2 as (
    SELECT * from cdr.Location
)

select * from cte1    
union     
select * from cte2

Błąd to

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

NB. Próbowałem wstawić średniki i uzyskać ten błąd

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ';'.

Prawdopodobnie nie ma znaczenia, ale to jest na SQL 2008.

Author: Scotty.NET, 2009-02-25

2 answers

Myślę, że powinno być coś w stylu:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cdr.Location)
select * from cte1 union select * from cte2

Zasadniczo, WITH jest tu tylko klauzulą i podobnie jak inne klauzule, które przyjmują listy,", " jest odpowiednim ogranicznikiem.

 121
Author: MarkusQ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-05 13:24:19

Powyższa odpowiedź jest słuszna:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cdr.Location)
select * from cte1 union select * from cte2

Dodatkowo, możesz również odpytywać z cte1 w cte2:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cte1 where val1 = val2)

select * from cte1 union select * from cte2

val1,val2 są tak samo jak wyrażenia..

Mam nadzieję, że ten blog również pomoże : http://iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html

 13
Author: Sagar Dev Timilsina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-14 19:46:10