【问题标题】:How to merge XML in T-SQL?如何在 T-SQL 中合并 XML?
【发布时间】:2009-12-01 21:10:41
【问题描述】:

似乎阅读文档对我没有任何帮助。考虑一个简化的例子:

declare @table1 table ( id int, parent xml )
insert @table1 values( 1, '<Root></Root>' )
declare @table2 table ( id int, guts xml )
insert @table2 values( 1, '<Guts>hi mom!</Guts>' )

select t1.parent.query('')
from @table1 t1 inner join @table2 t2 on t1.id = t2.id

将什么传递给查询函数以生成此结果?

<Root><Guts>hi mom!</Guts></Root>

【问题讨论】:

    标签: sql-server xml tsql


    【解决方案1】:

    以下不是基于设置的,但可能会有所帮助(仅限 SQL2008)

    declare @table1 table ( id int, parent xml )
    insert @table1 values( 1, '<Root></Root>' )
    declare @table2 table ( id int, guts xml )
    insert @table2 values( 1, '<Guts>hi mom!</Guts>' )
    
    DECLARE @id int;
    DECLARE @results table (id int, results xml);
    
    DECLARE idCursor CURSOR FOR 
        select id from @table1
    OPEN idCursor
    
    FETCH NEXT FROM idCursor INTO @id
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @parent xml, @guts xml
    
        SELECT @parent = parent FROM @table1 where id = 1;
        SELECT @guts = guts FROM @table2 where id = 1;
        SET @parent.modify('insert sql:variable("@guts") into (/Root[1])');
    
        INSERT @results (id, results) values (@id, @parent);
    
        FETCH NEXT FROM idCursor INTO @id
    
    END 
    
    CLOSE idCursor
    DEALLOCATE idCursor
    
    select * from @results;
    

    【讨论】:

    • 这很好,因为我不需要使用游标。
    • 为什么只有 SQL 2008? 2005也不行吗?顺便说一句,您需要在游标循环内的两个选择中使用@id。
    • 莱姆斯,你当然是对的。应该使用@id。我说 SQL 2008 只是因为这里报告的问题:tinyurl.com/lst3cz
    【解决方案2】:

    您要求的是 XML 操作,而不是关系操作。您想要的是通过插入一个 XML 片段来生成一个新的 XML,这意味着您必须使用 xml.modify() 方法。从技术上讲这是可能的,但是 modify() 必须 在更新上下文中调用,因此它在 SELECT 中不起作用。它可以在 SET 或 UPDATE 中工作:

    UPDATE t1
     SET parent.modify(N'insert sql:column("t2.guts") into (/Root)[1]')
    FROM @table1 t1
     JOIN @table2 t2 on t1.id = t2.id;
    SELECT * from @table1;
    

    如果您必须在 SELECT 中获得结果,那么您必须将 XML 分解为关系表,连接该表并使用 FOR XML 重新构建 XML。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2015-07-18
      • 2018-11-02
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      相关资源
      最近更新 更多