2013-05-21 148 views
0

我有一個表,其中有一個名爲「ServiceConfig」的數據類型爲xml的列。替換XML節點

我有一個XML格式的記錄如下圖所示:

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

現在,我想與<service name="pro" username="u" password="p"/>更換<service name="pro" />。所以得到的XML將是

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

我該如何實現它?

回答

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