Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql For Xml Path get node count

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.

like image 501
user355930 Avatar asked Feb 03 '26 14:02

user355930


1 Answers

How about drawing data from the CTE instead of the temp table?

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

This will allow you to keep your joins and search predicates in one place.

like image 196
8kb Avatar answered Feb 05 '26 07:02

8kb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!