【发布时间】:2017-03-30 02:24:11
【问题描述】:
我想在来自其他表的数据包含两行或更多行并且使用“用于 xml 路径”时显示数据,但在使用“用于 xml 路径”时始终为空。请立即查看我的示例表和我的 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
请帮助我...谢谢...
【问题讨论】:
-
IN不会读取字符串并且知道您正在寻找单独的值 - 它会将其视为单个字符串。您可用的解决方案是(a)规范化您的表(您应该这样做,而不是在列中保留逗号分隔值)并更改您的查询,(b)将您的IN更改为LIKE(例如WHERE ',' + a.IdReferensi + ',' LIKE '%,''' + IdRefensi + ''',%') 或 (c) 使您的查询动态化(比需要的更复杂)。
标签: sql-server subquery for-xml-path