简体   繁体   中英

How to return blank or null record when using STUFF and XML PATH on SQL Server 2016?

I am using STUFF and XML PATH as it is obligatory that I use SQL Server 2016. I have been working on this query and I cannot figure out how to return null or blank record when using STUFF and XML PATH. Below is the snippet of the query.

SELECT 
    Names = STUFF((SELECT '; ' + CONCAT(t3.FirstName, ' ', t3.LastName)
                   FROM table1 t1
                   LEFT JOIN table2 t2 ON t0.columnID = t2.columnID
                   LEFT JOIN table3 t3 ON t3.columnID = t3.columnID
                   FOR XML PATH('')), 1, 1,''),

The issue is that when there is no lastname/firstname, this query returns the separators '; ;' but I need it to return blank value if there is no lastname / firstname.

Just add a WHERE :

WHERE t3.FirstName IS NOT NULL OR t3.LastName IS NOT NULL

In this case, you probably also want to deal with one of them being null and getting an extra space:

SELECT '; ' + CASE
    WHEN t3.FirstName IS NOT NULL AND t3.LastName IS NULL THEN t3.FirstName
    WHEN t3.LastName IS NOT NULL AND t3.FirstName IS NULL THEN t3.LastName
    ELSE CONCAT(t3.FirstName, ' ', t3.LastName) END

Also, because your separator is two characters long, you need to change the STUFF parameters:
FOR XML PATH('')), 1, 2,'')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM