使用多个值的SQL Update语句

时间:2013-08-14 15:24:49

标签: sql sql-server-2008 tsql sql-update

我想更新名为Dash的表,我要更新的列名为Analysts。从下面的代码中我得到一个NameLast个人RoleId为3或4的人。此代码将首次出现在该人身上并将其姓氏插入Analysts ,但我想要的是所有Person RoleId 3或4的逗号分隔的姓氏列表。

    UPDATE Dash
    SET Dash.Analysts = Person.NameLast
    FROM dbo.Dash
    INNER JOIN dbo.Item 
    ON Dash.DPItem = Item.ItemId        
    INNER JOIN dbo.Assignment 
    ON Item.ItemId = Assignment.ItemId
    INNER JOIN dbo.Person
    ON Assignment.PersonId = Person.PersonId
    WHERE (Person.RoleId = 3 or Person.RoleId = 4)

1 个答案:

答案 0 :(得分:1)

update Dash set
    Analysts = 
    stuff(
         (
             select ', ' + P.NameLast
             from dbo.Item as I
                 inner join dbo.Assignment as A on A.ItemId = I.ItemId
                 inner join dbo.Person as P on P.PersonId = A.PersonId
             where I.ItemId = D.DPItem and P.RoleId in (3, 4)
             for xml path(''), type
         ).value('.', 'nvarchar(max)')
    , 1, 2, '')
from dbo.Dash as D