SQL Update Parent Table Field based on Multiple Ch

2019-07-16 03:26发布

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.

1条回答
乱世女痞
2楼-- · 2019-07-16 04:05
update parent
set longtext =
    stuff((
    select ',' + c.char + ': ' + c.val
    from child c
    where c.uid = parent.uid
    for xml path(''), type).value('.','nvarchar(max)'),1,1,'');

I have updated your SQLFiddle with the solution.

  1. STUFF() function to remove the leading ',' (comma) from the first characteristic.

  2. 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.

查看更多
登录 后发表回答