逗号分隔的列ID应显示值或文本(带有函数或查询)

时间:2015-04-27 08:05:16

标签: sql sql-server

我有一张这样的表

外国人表:

select * from table1
ID......NameIds
-------------------
1 ......1, 2 (its comma separated values)

主要表格(表格2)

ID  Name
-------------------
1      Cleo  
2      Smith

我想将表1显示为(我需要SQL函数或查询)

ID......NameIds
-------------------
1........Cleo, smith (show text/Name instead of values)

1 个答案:

答案 0 :(得分:1)

正如评论中所述 - 您应该重新考虑您的表格设计,但尝试为此编写查询非常有趣:

SELECT T1.ID, NameID, Name
INTO #Temporary
FROM #Table1 AS T1
CROSS APPLY (
    SELECT CAST(('<X>' + REPLACE(T1.NameIDs, ',', '</X><X>') + '</X>') AS XML)
    ) AS X(XmlData)
CROSS APPLY (
    SELECT NameID.value('.', 'INT')
    FROM XmlData.nodes('X') AS T(NameID)
    ) AS T(NameID)
INNER JOIN #Table2 AS T2
    ON T2.ID = T.NameID

SELECT ID, STUFF(T.Names, 1, 1, '') AS Names
FROM #Table1 AS T1
CROSS APPLY (
    SELECT ',' + Name
    FROM #Temporary AS T
    WHERE T.ID = T1.ID
    ORDER BY T.NameID
    FOR XML PATH('')
    ) AS T(Names)

<强>结果:

ID  Names
--------------
1   Cleo,Smith

它做什么,它将您的逗号分隔列表拆分为行,将它们连接到NameID,然后再次连接它们。猜猜那有多高效? 它可能不是最好的方法,但它确实有效。