SQL Server - CSV值的CSV值

时间:2016-04-05 09:54:08

标签: sql-server sql-server-2008 csv

我有2个表TableA,其中我有IDName

id  name
1   Turret Punch Press
2   Laser Machine
3   Press Brake
4   Other machines

Table B我将Id Table A作为CSV值传递给

id  TableACSV
1   1,2
2   1,3

我的查询类似

Select 
    id, TableACSV 
from tableB 
where (--here i am having problem with query--)

我想要的输出应该是这样的

id  TableACSV
1   Turret Punch Press,Laser Machine
2   Turret Punch Press,Press Brake

我知道这可能是一个不好的做法..但目前我需要这个..

1 个答案:

答案 0 :(得分:0)

使用CSV分割器DelimitedSplit8K

; WITH CTE AS
(
    SELECT  b.id, a.name
    FROM    TableB b
    CROSS APPLY dbo.DelimitedSplit8K(b.TableACSV, ',') c
    INNER JOIN TableA a on  c.Item  = a.id
)
SELECT  DISTINCT c.id, STUFF(d.name, 1, 1, '') AS TableACSV
FROM    CTE c
    CROSS APPLY
    (
        SELECT ',' + x.name
        FROM   CTE x
        WHERE  x.id = c.id
        FOR XML PATH ('')
    ) d (name)