2010-03-01 34 views
0

我想加入兩個SQL表,父母(我有完整的設計控制)和孩子(我不能改變)。我更改了父表,以便它具有一個varchar列,其中包含子記錄的ID的CSV列表。我現在想做一個選擇返回每父母一行,和一些計數器重新。孩子們(即有多少孩子具有真實的「地位」)。使用CSV值進行SQL連接?使用Xml也許?

我原本以爲我可以在CSV列表轉換成XML字符串,將它轉換爲XML類型的列,並使用XML「節點」加入子表 - 但我似乎無法得到語法正確。

任何人都可以建議如何做到這一點?

感謝, 羅斯

(這裏就是我一直在玩弄)

declare @true bit; set @true = ~0 
declare @false bit; set @false = 0 
declare @parent table (id int, children varchar(max)) 
declare @child table (id int, status bit) 

insert into @parent values (1,'1,2,3') 
insert into @child values (1,@true) 
insert into @child values (2,@false) 
insert into @child values (3,@false) 

;with parent as 
(
select id as 'parentId', cast('<children><child id="' + replace (children,',','"/><child id="') + '"/></children>' as xml) as 'children' from @parent 
) 
select parentId, t2.child.query('.') 
from parent 
--join @child as child on (child.id = ??) 
cross apply children.nodes('/children/child') as t2(child) 
+0

我知道我可以創建第三個表來交叉引用這兩個表,但我更感興趣的是使用CSV列表進行連接的可能技巧。 – 2010-03-01 11:24:01

回答

0

隨着多一點擺弄和谷歌搜索,我現在有這樣的:

declare @true bit; set @true = ~0 
declare @false bit; set @false = 0 
declare @parent table (id int, children varchar(max)) 
declare @child table (id int, status bit) 

insert into @parent values (1,'1,2,3') 
insert into @child values (1,@true) 
insert into @child values (2,@false) 
insert into @child values (3,@false) 
insert into @parent values (2,'4,5,6') 
insert into @child values (4,@true) 
insert into @child values (5,@false) 
insert into @child values (6,@false) 

;with parent as 
(
select id as 'id', cast('<children><child id="' + replace(children,',','"/><child id="') + '"/></children>' as xml) as 'children' from @parent 
) 
select parent.id 
    ,count(child.id) as 'children' 
    ,sum(case when child.status = @true then 1 else 0 end) as 'success' 
    ,sum(case when child.status = @false then 1 else 0 end) as 'failed' 
from parent 
cross apply children.nodes('/children/child') as t2(child) 
join @child as child on (child.id = t2.child.value('@id', 'int')) 
group by parent.id 

合理嗎?

謝謝。