Sql For Xml Path get node count

I am trying to use "for Xml Path" T-SQL to generate a comma-separated list of values ​​from a column. This seems to work fine, but the problem is that I would like to get the number of items in a comma-separated list. The following is sample code that I use to create a comma separated list:

Create Table #List ([col] varchar)

Insert Into #List Select '1';
Insert Into #List Select '2';
Insert Into #List Select '3'

Select ',' + [col] From #List For Xml Path('')

This gives results 1,2,3 as expected, but there is no way to get the score that there are 3 elements. Any attempt to add an account will simply add it to xml. I combined this code with cte to get the score:

With CTE As (
    Select 
        [col] 
    From 
        #List
)
Select
   (Select ',' + [col] From #List For Xml Path('')) As [List],
   Count(*) As [Count]
From
   CTE

/ CTE? , from , . , , , .

+3
2

CTE temp?

With CTE As (
    Select 
        [col] 
    From 
        #List
    -- Many joins
    -- Complicated where clause
)
Select
   (Select ',' + [col] From Cte For Xml Path('')) As [List],
   Count(*) As [Count]
From
   CTE

.

+2

CTE, .

SELECT 
      COUNT(*) AS [Count], 
      (SELECT ',' + [col] FROM #List FOR XML PATH('')) AS [List]
FROM #List
+1

Source: https://habr.com/ru/post/1763132/


All Articles