简体   繁体   中英

SQL Server : count XML Children within Parent

Hi I have been looking for a way of updating xml produced in sql to add the count of child nodes and add the count to the parent node using SQL

I've tried various workings around

    SET @xml.modify
    (
       'insert attribute TrCount {count(/XML/Acs/Act/Trs/Tr)} into (./XML/Acts/Act/Trs)'

);

    <XML>
      <Id>12</Id>
      <DateCreated>2013-04-11</DateCreated>
      <Acts AccountCount="4">
        <Act RowID="1>
             <Trs>
                 <Tr RowID="1" />
             </Trs>
         </Act>
         <Act RowID="2">
             <Trs>
                 <Tr RowID="1"  />
                 <Tr RowID="2" />
             </Trs>
          </Act>
          <Act RowID="3">
             <Trs>
                 <Tr RowID="1"/>
             </Trs>
          </Act>
          <Act RowID="4">
             <Trs>
                 <Tr RowID="1" />
                 <Tr RowID="2" />
                 <Tr RowID="3" />
                 <Tr RowID="4" />
                 <Tr RowID="5" />
                 <Tr RowID="6" />
                 <Tr RowID="7" />
           </Trs>
             </Act>
      </Acts>
    </XML>

above is a sample, I have got it to give me a count of within but I can not seem to get a count of each within each , so the result would look like

    <Act RowID="1>
          <Trs  Trcount="1">
            <Tr RowID="1" />
          </Trs>
        </Act>
        <Act RowID="2">
          <Trs  Trcount="2">
            <Tr RowID="1"  />
            <Tr RowID="2" />
          </Trs>
        </Act>
        <Act RowID="3">
          <Trs Trcount="1">
            <Tr RowID="1"/>
          </Trs>
        </Act>
        <Act RowID="4">
          <Trs Trcount="7">
            <Tr RowID="1" />
            <Tr RowID="2" />
            <Tr RowID="3" />
            <Tr RowID="4" />
            <Tr RowID="5" />
            <Tr RowID="6" />
            <Tr RowID="7" />
          </Trs>

Cheers

Try something like this, which assumes each Act contains only one Trs :

declare @count int = @xml.value('count(/XML/Acts/Act)', 'int'),
        @counter int = 1;

while (@counter <= @count)
begin
    SET @xml.modify ('insert attribute TrCount {count(/XML/Acts/Act[sql:variable("@counter")]/Trs/Tr)} into (/XML/Acts/Act[sql:variable("@counter")]/Trs)[1]');

    set @counter += 1;
end

insert() can only modify a singleton, not a whole set of nodes in one go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM