如何使用XQuery将xml插入另一个xml中的节点?

Him*_*dri 6 sql sql-server xquery sql-server-2005

我在SQL Server 2005的存储过程中有两个xml变量说@res,@ student.

@res包含

<Subject>English</Subject>
<Marks>67</Marks>
<Subject>Science</Subject>
<Marks>75</Marks>
Run Code Online (Sandbox Code Playgroud)

@student包含:

<Student> 
   <Name>XYZ</Name>
   <Roll>15</Roll>
   <Result />
   <Attendance>50</Attendance>
</Student>
Run Code Online (Sandbox Code Playgroud)

我需要使用XQuery 将@res的xml插入到@student变量的节点Result中.

如何实现?

请帮忙.

mar*_*c_s 32

在SQL Server 2008中,它非常简单:

DECLARE @res XML = '<Subject>English</Subject>
<Marks>67</Marks>
<Subject>Science</Subject>
<Marks>75</Marks>'


DECLARE @student XML = '<Student> 
   <Name>XYZ</Name>
   <Roll>15</Roll>
   <Result />
   <Attendance>50</Attendance>
</Student>'


SET @student.modify('insert sql:variable("@res") as first into (/Student/Result)[1]')

SELECT @student
Run Code Online (Sandbox Code Playgroud)

这给了我输出:

<Student>
  <Name>XYZ</Name>
  <Roll>15</Roll>
  <Result>
    <Subject>English</Subject>
    <Marks>67</Marks>
    <Subject>Science</Subject>
    <Marks>75</Marks>
  </Result>
  <Attendance>50</Attendance>
</Student>
Run Code Online (Sandbox Code Playgroud)

不幸的是,仅在SQL Server 2008中引入.modify()sql:variable在insert语句中调用和使用a 的能力- 在SQL Server 2005中不起作用.

我没有看到你如何在SQL Server 2005中做到这一点,除了回到丑陋的字符串解析和替换:

SET @student = 
    CAST(REPLACE(CAST(@student AS VARCHAR(MAX)), 
                 '<Result/>', 
                 '<Result>' + CAST(@res AS VARCHAR(MAX)) + '</Result>') AS XML)
Run Code Online (Sandbox Code Playgroud)


Tom*_*m H 6

这将在SQL 2005中工作,并且主要是xquery解决方案:

DECLARE @res xml

SET @res = 
'<Subject>English</Subject>
<Marks>67</Marks>
<Subject>Science</Subject>
<Marks>75</Marks>'

DECLARE @student xml
SET @student =
'<Student>
   <Name>XYZ</Name>
   <Roll>15</Roll>
   <Result />
   <Attendance>50</Attendance>
</Student>'

DECLARE @final XML

SET @final = CAST(CAST(@student AS VARCHAR(MAX)) + '<test>' + CAST(@res AS VARCHAR(MAX)) + '</test>' AS XML)

SET @final.modify('insert /test/* into (/Student/Result)[1]')
SET @final.modify('delete /test')

SELECT @final
Run Code Online (Sandbox Code Playgroud)

如果需要,可以在此时将@student变量设置为@final.节点的"test"名称就是我选择使用的名称.您可以使用任何名称,只要它不会出现在您的XML中.

您基本上只是将两个XML字符串放在一起,以便它们可以同时用于xquery.