Search code examples
sql-serversql-server-2012for-xml-path

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


I have a query like this:

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

I need to return a string with all values, including nulls, so that its amount of values is equal to amount of organizations, but if ALL values are empty or null, I need to return empty string or null (doesn't matter).

First thought was to use regex and check if there are digits in returned query. but it's not so easy to use. Is there some other options to solve it?

For example, if table Organization contains

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

then resulted string has to be '123456; -; 3232'

if table Organization contains

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

resulted string has to be null


Solution

  • Here's one way

    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