简体   繁体   English

在 SQL Server 2016 上使用 STUFF 和 XML PATH 时如何返回空白或 null 记录?

[英]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. 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

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:在这种情况下,您可能还想处理其中一个 null 并获得额外空间:

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:此外,由于您的分隔符是两个字符长,您需要更改STUFF参数:
FOR XML PATH('')), 1, 2,'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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