想在由逗号分隔的SQL表的列中插入多个值,

时间:2015-02-08 10:36:13

标签: sql sql-server

我想在SQL Server的单列中添加多个UCId。我正在使用Stuff,但结果显示所有UC ID而不是条件。

表:

UCId    UCPre                           UCPost                          UCNext (No column name)
-----------------------------------------------------------------------------------------------
UC01    User must be Registerd          User is Loggined sucessfully    UC02    UC03,UC05,UC02
UC02    User is Loggined sucessfully    User is added                   UC03    UC03,UC05,UC02
UC03    File must be selected           File is added                   NULL    UC03,UC05,UC02
UC04    File is added                   File is deleted                 NULL    UC03,UC05,UC02
UC05    User is Loggined sucessfully    User is deleted                 NULL    UC03,UC05,UC02

我正在使用以下查询:

SELECT 
    b.*,
    STUFF(
          (SELECT ',' + a.UCId 
           FROM UCDetails a, test b 
           WHERE (b.UCPost = a.UCPre)
           FOR XML PATH ('')),1,1,'') 
FROM 
    test b 
JOIN
    UCDetails a ON b.UCPost = a.UCPre

我想要的是什么:

我想在UC02和UC05的UC01 Id的UCNext列中用逗号(UC02,UC05)分隔,因为UC01的UCPost与UC02和UC05的UCPre匹配。

1 个答案:

答案 0 :(得分:0)

创建第三个表,可能称为NextUCId,其中包含两列:

UCId和UCNext

每个NextUCId都会列出一次相同的UCId:

UCId | UCNext
UC01 | UC02
UC01 | UC03

然后你可以在第三个表上进行连接,以获得UCId所需的UCNext ID,如下所示:

SELECT     uc.UCId,
           nuc.UCNext
FROM       UCId uc
INNER JOIN NextUCId nuc ON (uc.UCId = nuc.UCNext)
ORDER BY   nuc.UCNext ASC