Return string with each value separated or null if all are null, 使用 FOR XML PATH

Return string with each value separated or null if all are null, using FOR XML PATH

我有这样的查询:

select stuff (
        (select '; ' + isnull(org.Number, '-')
        from Organization org
        for xml path('')), 1, 2, ''
       )

我需要 return 一个包含所有值(包括空值)的字符串,以便其值的数量等于组织的数量,但是如果所有值都是空的或空的,我需要 return 空字符串或 null(无关紧要)。

首先想到的是使用正则表达式并检查 returned 查询中是否有数字。但它不是那么容易使用。还有其他解决办法吗?

例如,如果 table 组织包含

ID | Number
1  | 123456
2  | null
3  | 3232

那么结果字符串必须是 '123456; -; 3232'

如果table组织包含

ID | Number
1  | null
2  | null
3  | null

结果字符串必须是 null

这是一种方法

select
    iif(patindex('%[0-9]%', res) = 0, null, res)
from
    (select res = stuff((
        select
            '; ' + isnull(cast(number as varchar(200)), '-')
        from 
            Organization
        order by id
        for xml path('')
    ), 1, 2, '')
) t