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)