2017-03-01 7 views
1

ジャンクションテーブルを使用して多対多リレーションシップを持つSQL 2012のテーブルがあります。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