替换XML节点

时间:2013-05-21 09:17:36

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有一个表,其中有一个名为“ServiceConfig”的列,其数据类型为xml。

我有一个xml的记录,如下所示:

<Config>
  <services>
    <service name="pro" />
    <service name="postdata" />
  </services>
</Config>

现在,我想将<service name="pro" />替换为<service name="pro" username="u" password="p"/>。因此得到的XML将是

<Config>
  <services>
    <service name="pro" username="u" password="p"/>
    <service name="postdata" />
  </services>
</Config>

我如何实现它?

1 个答案:

答案 0 :(得分:2)

一种方法是添加像这样的新属性......

DECLARE @xmltest TABLE (ServiceConfig XML)
DECLARE @username VARCHAR(15) = 'u'
DECLARE @password VARCHAR(15) = 'p'
DECLARE @xml xml

INSERT @xmlTest values ('<Config>
                           <services>
                             <service name="pro" />
                             <service name="postdata" />
                           </services>
                         </Config>')

SELECT @xml = ServiceConfig from @xmltest

SET @xml.modify('insert (attribute username {sql:variable("@username")}, 
                         attribute password {sql:variable("@password")}) 
                         as last into (/Config/services/service)[1]')

UPDATE @xmltest SET ServiceConfig = @xml

SELECT * FROM @xmltest

Click here to go to SQL Fiddle demo of above code