OK, I'm looking at the problem of turning a set of records into a delimited list. It's an old problem, there are several approaches, and in many cases, I shouldn't even be doing this in the DB. But, in this case, I want to, and I want to use a recursive CTE.
And as my title might suggest, I'm frustrated by the difficulty that I'm having really grasping the concept. In the past, I've muddled through this problem with code snippets from books or internet posts and adapted them and gotten them to work. But it's always hard and I'm not really mastering the technique. I looked for a very basic implementation of the technique and landed at this answer that I'm using as a model: https://stackoverflow.com/a/9726839/13748
So right now, I have this temp table #POSO with the following contents:
id inspectionLogKey PO SO
--- ---------------- ------------- ---------
1 7 374534-6988 SO37047
2 7 374534-5464 SO34110
3 7 374534-7135 SO37377
4 7 374534-5284 SO33863
5 7 374534-6710 SO36506
6 7 374534-5084 SO33565
And from these data, I'd like to produce a comma-delimited list of the PO column's values. I'm trying to do that with this (and a bunch of frustrating permutations of this):
WITH POlists(id,POs) AS
(
SELECT p1.id, CONVERT(VARCHAR(MAX),p1.PO) as POs --anchor
FROM #POSO p1
WHERE p1.id = 1
UNION ALL
SELECT p2.id, POs + ',' + p2.PO --recursive
FROM #POSO p2
join POlists ON p2.id + 1 = POlists.id
)
SELECT * FROM POlists;
Which returns this:
id POs
--- -----------
1 374534-6988
I know that one of you is going to be able to point out the code error in the next eight minutes. But I'm hoping that someone can reframe what this is doing in such a way that I can actually grok it and take it away from this encounter as a tool for future use.
And maybe once that happens, I'll know enough to answer this on my own, but can this query handle both the PO and SO columns at the same time, producing two fields, each a comma-delimited list of the the two respective columns?
Thanks for your time!