道歉,如果这里有答案,但我找不到它......你能用FOR XML PATH连接多个表中的行吗?让我解释一下......
我有以下4个表格:
" BusinessSupport"其中涉及其他3个表
"应用程序"," BusinessProcess"和" OrgaUnit" (包含服务热线和地理位置等组织信息)
SELECT a.NAME AS [App Name],
STUFF((SELECT ',' + bp.NAME as [text()]
FROM BUSINESSPROCESS bp
LEFT JOIN BUSINESSSUPPORT bs on bp.REFSTR=bs.XOBJECT
WHERE bs.OBJECT=a.REFSTR FOR XML PATH('')), 1, 1, '' ) AS [Business Process] ,
STUFF((SELECT ',' + org.NAME as [text()]
FROM ORGAUNIT org
LEFT JOIN BUSINESSSUPPORT bs on org.REFSTR=bs.YOBJECT
WHERE bs.OBJECT=a.REFSTR FOR XML PATH('')), 1, 1, '' ) AS [Service Lines]
FROM APPLICATION a
这给了我表格结果,例如
APP1; process1,process2,process 3; SL1,SL2,SL3
APP2; process1,process 2; SL1,SL4,SL4
APP3; process4,过程2; SL3,SL5,SL6
但是,我现在有一个新的维度,我被要求报告。 表5"关系"其中提到了业务支持和Orgaunit。
我想要像
这样的东西APP1; process1,process2,process 3; SL1,SL2,SL3;地理1,地理2
APP2; process1,process 2; SL1,SL4,SL4;地理1,地理3
APP3; process4,过程2; SL3,SL5,SL6;地理3,地理4,地理5
我已尝试过以下操作但未返回任何结果:
STUFF((SELECT ',' + org2.name as [text()]
FROM ORGAUNIT org2
LEFT JOIN RELATIONS rel ON rel.TOREF=org2.name
LEFT JOIN BUSINESSSUPPORT bs on bs.REFSTR=rel.FROMREF
WHERE bs.OBJECT=a.REFSTR FOR XML PATH('')), 1, 1, '' ) AS [Geog]
由于
答案 0 :(得分:-1)
如果使用FOR XML
连接值时返回的任何列返回NULL,
,则整个连接字符串将变为NULL
,因为“some string”+ NULL
总是NULL
是SQL Server。如果您的示例中org2.name
可能是NULL
,则在连接结果周围包裹ISNULL
,并替换为空字符串。
STUFF((SELECT ISNULL(',' + org2.name, '') as [text()]
FROM ORGAUNIT org2
LEFT JOIN RELATIONS rel ON rel.TOREF=org2.name
LEFT JOIN BUSINESSSUPPORT bs on bs.REFSTR=rel.FROMREF
WHERE bs.OBJECT=a.REFSTR FOR XML PATH('')), 1, 1, '' ) AS [Geog]