简体   繁体   中英

Update xml specific nodes in table based on joining values in xml field with T-SQL

I must gave this problem a lot of time and searching. I even almost get the output, but the problem is the one to many join that is causing my problem. here is my data

--notice some of the Account nodes have elements that others don't
DECLARE @tbl TABLE(ID INT,fkey int, YourXML XML)

INSERT INTO @tbl (id, fkey, YourXML)
    SELECT 
        98, 8,
        N'<Params>
    <Account>
        <FirstName>Michael</FirstName>
        <LastName>Bar</LastName>
        <tcode>8</tcode>
    </Account>
    <Account>
        <FirstName>Pam</FirstName>
        <LastName>Bar</LastName>
    </Account>
</Params>'

    UNION 

    SELECT 
        99, 9, 
        N'<Params>
    <Account>
        <FirstName>Phil</FirstName>
        <LastName>Foo</LastName>
    </Account>
    <Account>
        <FirstName>Rebecca</FirstName>
        <LastName>Foo</LastName>
        <whatever>argh</whatever>
    </Account>
</Params>'

DECLARE @tbl2 TABLE(id INT, fkey INT, sfirst VARCHAR(255), slast VRACHAR(255))

INSERT INTO @tbl2 (id, fkey, sfirst, slast)
    SELECT 1, 8, 'Michael', 'Bar'
    UNION
    SELECT 2, 8, 'Pam', 'Bar'
    UNION
    SELECT 3, 9, 'Phil', 'Foo'
    UNION
    SELECT 4, 9, 'Rebecca', 'Foo'

--expected output

/* expected output
<Params>
    <Account>
        <FirstName>first1</FirstName>
        <LastName>last1</LastName>
        <tcode>8</tcode>
    </Account>
    <Account>
        <FirstName>first2</FirstName>
        <LastName>last2</LastName>
    </Account>
     <Account>
        <FirstName>first3</FirstName>
        <LastName>last3</LastName>
    </Account>
    <Account>
        <FirstName>first4</FirstName>
        <LastName>last4</LastName>
        <whatever>argh</whatever>
    </Account>
</Params>'
*/

The ultimate solution was code that looked like this, but did not keep variable xml tags like <tcode> that was in one account, and <whatever> that was in another

;WITH cte AS
(
    SELECT 
        YourXML,
        (SELECT DISTICNT
             'first' + REPLACE(STR(se.ID,9),' ','') AS FirstName,
             'last' + REPLACE(STR(se.ID,9),' ','') AS LastName
         FROM 
             @tbl AS sea
         INNER JOIN
             @tbl2 se ON sea.fkey = se.fkey
         CROSS APPLY 
             sea.YourXML.nodes(N'/Params/Account') AS x(nth)
         WHERE 
             sea.id = ilv.id
         FOR XML PATH('Account'), ROOT('Params'), TYPE) AS NewAdditionalInfo
    FROM 
        @tbl AS ilv
)
UPDATE cte 
SET YourXML = NewAdditionalInfo;

I then went on to execute a double nested while loop: 1 for the @tbl id and 2 for a count() on how many nodes.

I did notice that

update @tbl
set YourXML.modify('replace value of (//Account/FirstName/text())[sql:variable("@tenantcount")][1] with concat(sql:column("sfirst"),sql:column("ValTbl.id") cast as xs:string ?)')
....
where @tbl.id = @current_id

did work but again would victim to the one to many issue

thanks for the communities help

;WITH cte AS
(
    SELECT *
          ,(
                SELECT 
                t.YourXML
                        .query(N'/Params/Account[(FirstName/text())[1]=sql:column("sfirst") 
                                             and (LastName/text())[1]=sql:column("slast")]')
                        .query(N'<Account>
                                 {
                                    for $nd in /Account/*
                                    return 
                                    if(local-name($nd)="FirstName") then
                                        <FirstName>{concat("first"[1],xs:string(sql:column("t2.id")))}</FirstName>
                                    else if(local-name($nd)="LastName") then
                                        <LastName>{concat("last"[1],xs:string(sql:column("t2.id")))}</LastName>
                                    else
                                    $nd
                                 }  
                                 </Account> ') AS [*]
                FROM tbl AS t
                INNER JOIN tbl2 AS t2 ON t.fkey=t2.fkey
                where t.id = tt.id
                ORDER BY t2.id
                FOR XML PATH(''),ROOT('Params'),TYPE
           ) AS NewXML
    FROM tbl AS tt
)
update cte set YourXML = NewXML
select * from tbl

What about this:

SELECT t.YourXML
        .query(N'/Params/Account[(FirstName/text())[1]=sql:column("sfirst") 
                             and (LastName/text())[1]=sql:column("slast")]')
        .query(N'<Account>
                 {
                    for $nd in /Account/*
                    return 
                    if(local-name($nd)="FirstName") then
                        <FirstName>{concat($nd/text()[1],xs:string(sql:column("t2.id")))}</FirstName>
                    else if(local-name($nd)="LastName") then
                        <LastName>{concat($nd/text()[1],xs:string(sql:column("t2.id")))}</LastName>
                    else
                    $nd
                 }  
                 </Account> ') AS [*]
FROM @tbl AS t
INNER JOIN @tbl2 AS t2 ON t.fkey=t2.fkey
ORDER BY t2.id
FOR XML PATH(''),ROOT('Params');

The result

<Params>
  <Account>
    <FirstName>Michael1</FirstName>
    <LastName>Bar1</LastName>
    <tcode>8</tcode>
  </Account>
  <Account>
    <FirstName>Pam2</FirstName>
    <LastName>Bar2</LastName>
  </Account>
  <Account>
    <FirstName>Phil3</FirstName>
    <LastName>Foo3</LastName>
  </Account>
  <Account>
    <FirstName>Rebecca4</FirstName>
    <LastName>Foo4</LastName>
    <whatever>argh</whatever>
  </Account>
</Params>

Some explanation

XML's .query() allows to put this in serie:

SomeXML.query(N'XQuery').query(N'OtherXQuery')

The first .query() uses sql:column to filter the <Account> where FirstName and LastName are equal to sfirst and slast .
The next .query() uses a FLWOR query to travers through all nodes below <Account> and return them depending in their name.
Doing this, other nodes are just passed through...

T-SQL's XQuery is rather limited, you cannot define new elements or attributes dynamically, nor can you create the structure generically, but you can do quite a lot :-D

This does not update the original table but it returns exactly your expected output.

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