0

I have a table in which there is a column named "ServiceConfig" with datatype xml.

I have a record with xml like below :

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

Now, I want to replace <service name="pro" /> with <service name="pro" username="u" password="p"/>. So the resultant XML will be

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

How do I achieve it?

1 Answer 1

2

One way would be to add the new attributes like this...

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.