逗号分隔值加入到 master table

Comma separated values join to master table

我想在来自其他 table 的数据有两行或更多并且与 "for xml path" 为一行时显示数据,但在使用 "for xml path" 时始终为空。请现在查看我的示例 table 和我的 sql 查询。

TCPAR :
IdCPAR | IdReferensi 
1        '1','2'
2        '1','3','4'

TReferensi :
IdReferensi | Referensi
1              Alfa
2              Beta 
3              Carlie
4              Delta

i want result like this:
IdCpar | IdReferensi | ReferensiName
1         '1','2'      'Alfa','Beta'

这是我的 sql 查询:

select
a.idCpar,
a.IdReferensi,
(
    SELECT LEFT(result, Len(result) - 1) FROM(SELECT '''' + Referensi + ''',' FROM TReferensi (NOLOCK) 
    WHERE IdReferensi IN (a.IdReferensi)
    ORDER  BY Referensi FOR XML PATH ('')) x (result)
)as ReferensiName
from TCPAR as a
where a.IdCPAR=1

and the result:
idCpar | IdReferensi | ReferensiName
1          '1','2'     NULL

请帮助我...谢谢...

试试这个

select
a.idCpar,
a.IdReferensi,
STUFF(
   (SELECT CONCAT(',''', Referensi , '''') FROM TReferensi (NOLOCK) 
   WHERE a.IdReferensi LIKE CONCAT('%''',IdReferensi,'''%')
   ORDER  BY Referensi FOR XML PATH ('') )
,1,1,'') as ReferensiName
from TCPAR as a
where a.IdCPAR=1
CREATE TABLE TReferensi
    ([IdReferensi] int, [Referensi] varchar(6))
;


INSERT INTO TReferensi
    ([IdReferensi], [Referensi])
VALUES
    (1, 'Alfa'),
    (2, 'Beta'),
    (3, 'Carlie'),
    (4, 'Delta')
;

CREATE TABLE TCPAR
    ([IdCPAR] int, [IdReferensi] varchar(100))
;

INSERT INTO TCPAR
    ([IdCPAR], [IdReferensi])
VALUES
    (1, '''1'',''2'''),
    (2, '''1'',''3'',''4''')
;



;with cte as
(
    select
        t1.IdCPAR, t2.IdReferensi
    from
    (
        select
            IdCPAR, 
            IdReferensi = cast(cast(t2.c.query('data(.)') as varchar) as int)
        from
        (
            select 
                IdCPAR,
                ReferensiXml = cast('<root><a>' + replace(REPLACE(IdReferensi,'''',''), ',', '</a><a>') + '</a></root>' as xml)
            from TCPAR
        ) t1
        cross apply ReferensiXml.nodes('/root/a') t2(c)
    ) t1
    join TReferensi t2 on t1.IdReferensi = t2.IdReferensi
)



SELECT T2.IdCPAR,T3.IdReferensi,
        STUFF((SELECT ','''+Referensi+''''
        FROM (
                select 
                    t1.IdCPAR,t2.Referensi
                from cte t1
                INNER JOIN TReferensi t2 
                ON  t2.IdReferensi = t1.IdReferensi 
             )T1
        WHERE T2.IdCPAR = T1.IdCPAR
        FOR XML PATH('')),1,1,'') AS Referensi
FROM(
    select 
        t1.IdCPAR,t2.Referensi
    from cte t1
    INNER JOIN TReferensi t2 
    ON  t2.IdReferensi = t1.IdReferensi 
 )T2
INNER JOIN TCPAR T3
 ON T3.IdCPAR = T2.IdCPAR
GROUP BY T2.IdCPAR,T3.IdReferensi

Demo