2017-03-01 2 views
1

SQL2004에는 연결 테이블을 통해 자체 관계가 많은 테이블이 있습니다.SQL Server 2012에서 다 대다 관계를 반복적으로 쿼리하는 방법

enter image description here

내가 말하는 겁니다 많은 관계로 많은 Currency_Dependency 인을 다음과 같이이 배치입니다.

내가 뭘하고 싶은 건 트리 형태로 모든 종속성을 표시하는 재귀 쿼리를 작성하는 것이므로 각 관계는 선택되는 기본 통화 항목에서 몇 단계 떨어져 있는지를 나타내는 숫자로 표시됩니다. 어떤 지류인지 식별하는 번호. 가능한 경우이 쿼리를 두 가지 방법으로 사용하여 원하는 통화 항목 (상위 통화 항목)과 하위 항목 (하위 통화 항목)에 의존하는 모든 통화 항목을 표시합니다. 첫 번째 수준 만 표시하는 쿼리가 있습니다. 그래서 나는 그것이 루트 통화 항목에서 여러 단계를 어떻게 나타내는 그 수와 부모와 자식 종속성 추가 열을하고자 이러한 결과

enter image description here

을 생산

SELECT curr.Model AS 'Root Currency Item', cur2.Model AS 'Child Currency Item', cur3.Model AS 'Parent Currency Item' 
FROM dbo.Currency curr 
FULL JOIN dbo.Currency_Dependency cdep 
ON curr.CurrencyId = cdep.CurrencyId 
FULL JOIN dbo.Currency cur2 
ON cdep.DependencyId = cur2.CurrencyId 
FULL JOIN dbo.Currency_Dependency cdep2 
ON curr.CurrencyId = cdep2.DependencyId 
FULL JOIN dbo.Currency cur3 
ON cdep2.CurrencyId = cur3.CurrencyId 
WHERE curr.Status = 1 AND NOT(cur2.Model IS null AND cur3.Model IS null) 

. 나는 그것이 의미가 있기를 바랍니다.

그런 쿼리가 가능합니까? 나는 공통 테이블식이 재귀 쿼리에 사용되는 것이지만 지금까지 읽은 모든 것은 꽤 그리스어였습니다 (저는 2 학년 컴퓨터 프로그래밍 학생입니다)

알려 주시기 바랍니다. 네가 도울 수 있다면! 정말 고마워! 예를 들어 데이터없이

답변

1

내가 확신 할 수는 없지만, 나는이 생각하는 당신이 무엇인지 후 :

;with cte as (
-- anchor elements: where curr.Status = 1 and not a dependent 
    select 
     CurrencyId 
    , Model 
    , ParentId  = null 
    , ParentModel = convert(varchar(128),'') 
    , Root   = curr.Model 
    , [Level]  = convert(int,0) 
    , [Path]  = convert(varchar(512),Model) 
    from dbo.Currency as curr 
    where curr.Status = 1 
    /* anchors do not depend on any other currency */ 
    and not exists (
     select 1 
     from dbo.Currency_Dependency i 
     where curr.CurrencyId = i.DependencyId 
    ) 
    -- recursion begins here 
    union all 
    select 
     CurrencyId = c.CurrencyId 
    , Model  = c.Model 
    , ParentId  = p.CurrencyId 
    , ParentModel = convert(varchar(128),p.Model) 
    , Root   = p.Root 
    , [Level]  = p.[Level] + 1 
    , [Path]  = convert(varchar(512),p.[Path] + ' > ' + c.Model) 
    from dbo.Currency as c 
    inner join dbo.Currency_Dependency as dep 
     on c.CurrencyId = dep.DependencyId 
    inner join cte as p 
     on dep.CurrencyId = p.CurrencyId 
) 
select * from cte 
+0

와우, 브릴리언트! 정말 고맙습니다! – David

+1

@David 도와 드리겠습니다! – SqlZim