I have the following sample table structures for a parent
/ child
relationship.
parent
table
id LongText
--------------
10
20
child
table
id char value
--------------------
10 COLOR RED
10 HEIGHT 1FT
20 COLOR BLUE
20 WIDTH 2FT
I have a requirement that specifies that certain fields from the child table rows need to be concatenated together and placed in the parent table. I would like to complete this in a single SQL query if possible. The update statement that I have written is as follows.
UPDATE
parent
SET
LongText = COALESCE(LongText, N'')
+ child.char + N': ' + child.val + ','
FROM
parent INNER JOIN child
ON
parent.id = child.id
But I only get the following results.
id LongText
------------------
10 COLOR: RED,
20 COLOR: BLUE,
I would expect (or I should say I WANT) to get this.
id LongText
------------------
10 COLOR: RED,HEIGHT: 1FT
20 COLOR: BLUE,WIDTH: 2FT
Is this possible? Any suggestions as to how I can do this? Any help is appreciated!
Here is a SQLfiddle for reference.
I have updated your SQLFiddle with the solution.
STUFF() function to remove the leading
','
(comma) from the first characteristic.FOR XML to create an XML document from a query result. This is a well known trick with SQL Server - because the column is not named, there is no element produced and only the raw text (of each row) is output, mashed together into a single row.
Very few articles on the internet attempt to explain it in detail, since the code is pretty much left as an explanation in and of itself.