Concatenate Rows using FOR XML PATH() from multiple tables

北战南征 提交于 2019-12-25 01:41:45

问题


Apologies if there was an answer in here, but I cannot find it...Can you concatenate rows from multiple tables using FOR XML PATH. Let me explain....

I have the following 4 tables:

"BusinessSupport" which has reference to the other 3 tables

"Application", "BusinessProcess" and "OrgaUnit" (contains organizational info such as Service Line and Geography)

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 

This gives me table results such as

AppName; Business Process; Service Lines

app1; process1, process2, process 3; SL1, SL2, SL3

app2; process1, process 2; SL1, SL4, SL4

app3; process4, process 2; SL3, SL5, SL6

However, I now have a new dimension I have been asked to report from. Table 5 "Relations" which has a reference to Business Support and Orgaunit.

I would like to have something like

AppName; Business Process; Service Lines; Geography

app1; process1, process2, process 3; SL1, SL2, SL3; Geography1, Geography2

app2; process1, process 2; SL1, SL4, SL4; Geography1, Geography3

app3; process4, process 2; SL3, SL5, SL6; Geography3, Geography4, Geography5

I have tried the following but do not get any results returned:

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]

Thanks


回答1:


If any of your columns returned when using FOR XML to concatenate values return a NULL, then the entire concatenated string will become NULL, since "some string" + NULL is always NULL is SQL Server. If it is possible for org2.name to be NULL in your example, then wrap an ISNULL around the concatenated results, and replace with an empty string.

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]


来源:https://stackoverflow.com/questions/26758458/concatenate-rows-using-for-xml-path-from-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!