Hi and thanks in advance.
First off, I do not mean I want to convert an array into a table. I can do that. Easy :)
I would like to do the opposite.
I have a row with n rows related to it in another table. I wish to output the row and then within a single column of that row, let's say Children
, its linked rows in an array (or a string that I can interpret as an array with front-end code).
Like this:
ID TITLE DESCRIPTION CHILDREN
--------------------------------------------------------
36 Blah Blah Blah ['Bob','Gary','Reginald']
20 Pah Pah Pah ['Emily','Dave']
You see?
I know, this is probably not the best way to do it. But, it's for a specific use that would be too long to explain here.
Thanks again.
You need a function that when passed the foreign key that links the child table to the parent, queries the child table to build a cursor and then loops through it concatenating the required values. Function then returns that string. Function is then called as the fourth column of your query. Can't help you with the syntax etc as I don't use SQL-Server
There are multiple ways to do it; the article below presents various solutions for this type of operation:
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
You can actually do this all in one CTE select query, without using any functions. Here's how:
First, consider this parent/child table structure:
(I've use P and C to save on typing!)
And lets add some test data, matching that of the question asker:
Then finally, the CTE expression:
Result:
To explain what's going on here, I'll describe each part of the CTE and what it does.
FirstItems looks at all the children, and finds the lowest ID in each parent group to use as the anchor for the next recursive SELECT:
SubItemList is a recursive SELECT that picks up the lowest child from the previous query, and allocates an incrementing item number to each child starting from 1:
The trouble is it dups up and repeats a lot of the items, so ItemList filters it to just pick the max from each group:
Now we have an ID list of parents with each of there children numbered from 1 to x:
SubArrayList takes the children rows, recursively joins to the numbers list and starts appending all the descriptions to each other, starting with a single description:
The result is now:
So all we need to do is to get rid of all the partly concatenated rows.
MaxItems simply grabs a list of parents and their highest item numbers, which makes the following query a bit simpler:
ArrayList performs the final cull of the partly concatenated rows using the max item number aquired from the previous query:
And finally, all that remains is to query the result: