programing

단일 SELECT 문에 공통 테이블 식을 여러 개 사용하려면 어떻게 해야 합니까?

yoursource 2023. 5. 7. 21:14
반응형

단일 SELECT 문에 공통 테이블 식을 여러 개 사용하려면 어떻게 해야 합니까?

복잡한 select 문을 단순화하는 중이라 일반적인 표 표현을 사용하려고 합니다.

단일 ct를 선언하는 것은 잘 작동합니다.

WITH cte1 AS (
    SELECT * from cdr.Location
    )

select * from cte1 

동일한 SELECT에서 둘 이상의 ct를 선언하고 사용할 수 있습니까?

이 SQL은 오류를 제공합니다.

WITH cte1 as (
    SELECT * from cdr.Location
)

WITH cte2 as (
    SELECT * from cdr.Location
)

select * from cte1    
union     
select * from cte2

잘못은

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. 세미콜론을 넣으려고 시도했지만 이 오류가 발생했습니다.

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

관련이 없을 수도 있지만 SQL 2008에 대한 내용입니다.

저는 다음과 같은 것이어야 한다고 생각합니다.

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

기본적으로,WITH는 여기서 절일 뿐이며 목록을 사용하는 다른 절과 마찬가지로 ","가 적절한 구분 기호입니다.

위에서 언급한 답은 옳습니다.

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

또한 cte2의 cte1에서 쿼리할 수도 있습니다.

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

select * from cte1 union select * from cte2

val1,val2표현에 대한 추측일 뿐입니다.

이 블로그가 또한 도움이 되기를 바랍니다: http://iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html

언급URL : https://stackoverflow.com/questions/584284/how-can-i-have-multiple-common-table-expressions-in-a-single-select-statement

반응형