SQL Server - 仅使用.modify()合并两个XML

时间:2016-01-29 09:26:36

标签: sql sql-server xml tsql xpath

假设我们有:

CREATE TABLE #Users(id INT PRIMARY KEY, name VARCHAR(100), suggestions XML);

INSERT INTO #Users(id, name, suggestions)
SELECT 1, 'Bob', N'<Products>
                     <Product id="1" score="1"/>
                     <Product id="2" score="5"/>
                     <Product id="3" score="4"/>
                   </Products>'
UNION ALL
SELECT 2, 'Jimmy', N'<Products>
                       <Product id="6" score="3"/>
                     </Products>';

DECLARE @userId INT = 1,
        @suggestions XML = N'<Products>
                              <Product id="2" score="5"/>
                              <Product id="3" score="2"/>
                              <Product id="7" score="1" />
                             </Products>';

Playground

现在我想基于id属性合并2个XML:

id = 1的用户的最终结果:

<Products>
  <Product id="1" score="1"/> -- nothing changed (but not exists in @suggestions)
  <Product id="2" score="5"/> -- nothing changed (but exists in @suggestions)
  <Product id="3" score="2"/> -- update score to 2
  <Product id="7" score="1"/> -- insert new element
</Products>

请注意,它并没有组合2个XML,而是&#34; upsert&#34;操作

说明:

  • 我知道这种架构违反了数据库规范化并且规范化是一种方法(但不是在这种情况下)
  • 我知道利用派生表,.nodes().value()函数的解决方案首先解析XML,然后合并并写回来

我正在搜索is XPath/XQuery表达式,它将在一个语句中合并它(没有派生表/ dynamic-sql *):

*如果绝对需要,可以使用动态SQL,但我想避免使用它。

UPDATE #Users
SET suggestions.modify(... sql:variable("@suggestions") ...); --changes only here
WHERE id = @userId;


/* replace ... for ... where ... with sql:variable */

4 个答案:

答案 0 :(得分:4)

经过一段时间的努力,我认为这是不可能的......

这里有类似的问题:XQuery adding or replacing attribute in single SQL update command

.modify(insert Expression1 ... )不允许通过@sql:variable()sql:column()

传入通过传入的XML中的数据

在此处阅读:{1}}在Expression1 - &gt; “常量XML或独立的sql:column / sql:variable或XQuery(到同一个实例)

DECLARE @xml1 XML= --the existing XML
'<Products>
  <Product id="1" score="1" />
  <Product id="2" score="5" />
  <Product id="3" score="4" />
</Products>';

DECLARE @xml2 XML= --the XML with new or changed data
'<Products>
  <Product id="2" score="5" />
  <Product id="3" score="2" />
  <Product id="7" score="1" />
</Products>';

SET @xml1.modify('insert sql:variable("@xml2") as first into /Products[1]');

SELECT @xml1;

/* The full node is inserted!
Without any kind of preparation there is NO CHANCE to get the inner nodes only

<Products>
  <Products>
    <Product id="2" score="5" />
    <Product id="3" score="2" />
    <Product id="7" score="1" />
  </Products>
  <Product id="1" score="1" />
  <Product id="2" score="5" />
  <Product id="3" score="4" />
</Products>
*/

您可以声明第二个XML:

DECLARE @xml2 XML= --the XML with new or changed data
'<Product id="2" score="5" />
 <Product id="3" score="2" />
 <Product id="7" score="1" />';

但是你没有机会将id的值用作XQuery过滤器

SET @xml1.modify('insert sql:variable("@xml2") as first into /Products[**How should one filter here?**]');

最后但并非最不重要的是,我认为在.modify()的一次调用中没有机会合并两个不同的XML_DML语句。

我唯一的想法就是这个,但它不起作用。 IF似乎只能在 表达式中使用,但不能区分两个执行路径

SET @xml1.modify('if (1=1) then
                     insert sql:variable("@xml2") as first into /Products[1]
                  else
                     replace value of /Products[1]/Product[@id=1][1]/@score with 100');

所以我的结论是:不,这是不可能的......

我在这里提供的解决方案https://msdn.microsoft.com/en-us/library/ms175466.aspx在第二部分(“如果你想'合并'两个书籍结构”)将是我解决这个问题的方法。

答案 1 :(得分:0)

尝试这样的事情,很容易理解,但是很冗长。

如果您有任何问题,请告诉我。

declare @Users TABLE(id INT PRIMARY KEY, name VARCHAR(100), suggestions XML);

INSERT INTO @Users(id, name, suggestions)
SELECT 1, 'Bob', N'<Products>
                     <Product id="1" score="1"/>
                     <Product id="2" score="5"/>
                     <Product id="3" score="4"/>
                   </Products>'
UNION ALL
SELECT 2, 'Jimmy', N'<Products>
                       <Product id="6" score="3"/>
                     </Products>';

DECLARE @userId INT = 1,
        @suggestions XML = N'<Products>
                              <Product id="2" score="5"/>
                              <Product id="3" score="2"/>
                              <Product id="7" score="1" />
                             </Products>';

declare @Users1 TABLE(userid INT , productid int,score int);
insert into @Users1 
SELECT id userid,
    t.c.value('(@id[1])', 'VARCHAR(50)') AS Productid,
    t.c.value('(@score[1])', 'VARCHAR(50)') AS score

FROM @Users yt
    cross APPLY yt.suggestions.nodes('Products/Product') t(c)
--select * from @Users1
;With CTE1 as
(
    select @userId userid,
    t.c.value('(@id[1])', 'VARCHAR(50)') AS Productid,
    t.c.value('(@score[1])', 'VARCHAR(50)') AS score
   from @suggestions.nodes('Products/Product') t(c)
)

Merge @users1 as trg
using cte1 as src
 on trg.userid=src.userid and trg.productid=src.productid
when not matched then
insert (userid,productid,score) values(src.userid,src.productid,src.score);

select distinct a.userid
 ,(select b.productid as '@Productid',b.score as '@Score'  
from @users1 b where a.userid=b.userid  
for xml path('Product'),root('Products'))  
from @users1 a

答案 2 :(得分:0)

这不是你所希望的优雅单线。不过,它有点工作,所以我会分享。 (而且我确信还有改进的余地。)

    IF OBJECT_ID('tempdb..#Users') IS NOT NULL DROP TABLE #Users

    CREATE TABLE #Users(id INT PRIMARY KEY, name VARCHAR(100), suggestions XML);

    INSERT INTO #Users(id, name, suggestions)
    SELECT 1, 'Bob', N'<Products>
                 <Product id="1" score="1"/>
                 <Product id="2" score="5"/>
                 <Product id="3" score="4"/>
               </Products>'
    UNION ALL
    SELECT 2, 'Jimmy', N'<Products>
                           <Product id="6" score="3"/>
                         </Products>';

    --@Suggestions is slightly different (note the "<Products>" parent element is gone).
    DECLARE @userId INT = 1,
            @suggestions XML = N' <Product id="2" score="5"/>
                                  <Product id="3" score="2"/>
                                  <Product id="7" score="1" />';

    --Capture the original suggestions so we can compare later
    DECLARE @OldXML As XML = (SELECT suggestions from #Users where id = @userId)

    UPDATE #Users   --this inserts the new suggestions (we delete old ones as needed, below).
    SET suggestions.modify('insert sql:variable("@suggestions") as first into /Products[1]')
    WHERE id = @userId;

    WHILE (@OldXML.exist('/Products/Product') = 1)
      BEGIN  --For each of the user's original Products, delete the second instance of it.
        DECLARE @prodId int = (SELECT @OldXML.value('(/Products/Product/@id)[1]', 'nvarchar(max)') FROM #Users where id = @userId)
        UPDATE #Users SET suggestions.modify('delete /Products/Product[@id= sql:variable("@prodId")][2]') WHERE id = @userId
        SET @OldXML.modify('delete /Products/Product[@id=sql:variable("@prodId")][1]')
      END

    SELECT * FROM #Users where id = @userId
    DROP TABLE #Users

答案 3 :(得分:0)

我认为你可以使用这样的查询:

UPDATE #Users
SET suggestions = (
    SELECT id, score
    FROM
        (SELECT 
            *,
            ROW_NUMBER() OVER (PARTITION BY id ORDER BY ord) As seq
        FROM (
            SELECT 
                c.value('@id', 'INT') AS id,
                c.value('@score', 'INT') AS score,
                1 As ord
            FROM
                @suggestions.nodes('/Products/Product') As t(c)
            UNION ALL
            SELECT 
                c.value('@id', 'INT') AS id,
                c.value('@score', 'INT') AS score,
                2 as ord
            FROM
                (SELECT suggestions x FROM #Users WHERE id = @userId) As u CROSS APPLY
                u.x.nodes('/Products/Product') As t(c)) dt) Product
    WHERE seq = 1
    FOR XML AUTO, ROOT('Products'))
WHERE
    (id = @userId);

SELECT * 
FROM #Users;

<强> [Playground]