簡體   English   中英

SQL聯接/合並兩個architectureid表

[英]SQL join/merge two hierarchyid tables

有沒有辦法在SQL Server中聯接/合並兩個層次表?

我有兩個示例表: BOMComponentDetail

declare @BOM table 
    (
      BomNode hierarchyid primary key,
      ComponentID int
    )

insert into @BOM 
values
    ('/',             NULL),
    ('/1/',           1),
    ('/1/1/',         2),
    ('/1/2/',         3),
    ('/1/3/',         4)

declare @ComponentDetail table
   (
       CompNode hierarchyid primary key,
       ComponentID int,
       SteelProductID int
   )

insert into @ComponentDetail 
values
   ('/',          NULL,NULL),
   ('/1/',        2, NULL),
   ('/1/1/',      2,1),
   ('/1/2/',      2,2)

我想要做的是臨時合並這兩個表,只是為了在我的應用程序中查看結果:

更新:@Sean Lange我在聲明結果表時犯了一個錯誤-它看起來應該像下面這樣:

insert into @Result 
    values 
       ('/',     NULL, NULL),
       ('/1/',   1, NULL),
       ('/1/1/',   2, NULL),
       ('/1/1/1/', NULL, 1),
       ('/1/1/2/', NULL, 2),
       ('/1/2/',   3, NULL),
       ('/1/3/',   4, NULL)

select 
    Node.ToString() as NodeChar, ComponentID, SteelProductID 
from @Result

這是所需輸出的圖: 輸出圖

任何人 ?

您可以像其他任何表一樣將這兩個表連接在一起。 在這種情況下,可能需要完全外部聯接。

這將從樣本數據中返回所需的輸出:

select Node = coalesce(b.BomNode.ToString(), c.CompNode.ToString())
    , ComponentID = coalesce(b.ComponentID, c.ComponentID)
    , c.SteelProductID
from @BOM b
full outer join @ComponentDetail c on c.CompNode = b.BomNode

- 編輯 -

根據我的新理解,我認為它是這樣的(但是在層次結構方面並不完全正確,但對我來說不清楚您想要什么):

select distinct Node = coalesce(b.BomNode.ToString(), c.CompNode.ToString()) + coalesce(convert(varchar(4), c.ComponentID) + '/', '')
    , ComponentID = coalesce(b.ComponentID, c.ComponentID)
    , c.SteelProductID
from @BOM b
full outer join @ComponentDetail c on b.ComponentID = c.ComponentID 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM