开发者

Sql For Xml Path get node count

I'm tryin开发者_开发问答g 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.


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.


You don't need the CTE you can use the subquery approach directly

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜