tags:

views:

134

answers:

1

Hi,

I'm trying to join two SQL tables, parent (which I have complete design control over) and child (which I cannot change). I have changed the parent table so that it has a varchar column, containing a CSV list of the ids of the child records. I would now like to do a select returning one row per parent, and some counters re. the children (ie. how many children have a "status" of true).

I had originally thought that I could convert the CSV list into an Xml string, cast it to a column of type Xml, and join the child table using the Xml "nodes" - but I can't seem to get the syntax right.

Can anyone suggest how this could be done ?

Thanks, Ross

(here's what I've been toying with)

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)
A: 

With a bit more fiddling and Googling, I now have this:

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

Reasonable ?

Thanks.

Ross Watson