我有一个表,其中有一个名为“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>
我如何实现它?
答案 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