I'm trying to use the 'For Xml Path' T-SQL to generate a comma separated list of values from a column. This seems to work great, but the problem is I would like to get a count of the items in the comma separated list. Here is an example of the code I am using to generate the 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 the results 1,2,3 as expected, but there is no way to get the count that there are 3 items. Any attempt to add a count will just add it to the xml. I combined this code with a cte to get the count:
With CTE As (
Select
[col]
From
#List
)
Select
(Select ',' + [col] From #List For Xml Path('')) As [List],
Count(*) As [Count]
From
CTE
Is there an easier/cleaner way to get the count of nodes without using a CTE? It was pointed out that you can just duplicate the from clause inside the inner select and outside, but that requires keeping the from clauses in sync. I want to get both the list and count, but only have the from clause written once.