使用CSV值进行SQL连接?也许使用Xml?

使用CSV值进行SQL连接?也许使用Xml?,sql,xml,nodes,Sql,Xml,Nodes,我正在尝试连接两个SQL表,父表是我可以完全控制设计的,子表是我无法更改的。我更改了父表,使其具有一个varchar列,其中包含子记录ID的CSV列表。我现在想做一个select,每个父对象返回一行,并重新设置一些计数器。孩子们,也就是说,有多少孩子的身份是真实的 我原本以为我可以将CSV列表转换为Xml字符串,将其转换为Xml类型的列,并使用Xml节点连接子表,但我似乎无法获得正确的语法 有人能建议如何做到这一点吗 谢谢, 罗斯 这是我一直在玩的东西 通过更多的拨弄和谷歌搜索,我现在有了这个:

我正在尝试连接两个SQL表,父表是我可以完全控制设计的,子表是我无法更改的。我更改了父表,使其具有一个varchar列,其中包含子记录ID的CSV列表。我现在想做一个select,每个父对象返回一行,并重新设置一些计数器。孩子们,也就是说,有多少孩子的身份是真实的

我原本以为我可以将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)
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
合理吗


谢谢。

我知道我可以创建第三个表来交叉引用这两个表,但我更感兴趣的是使用CSV列表进行连接的可能技术。
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