1

I have a table with an XML column. I need to insert various nodes and then set those nodes using values from a sub-query.

Setup:

use tempdb
CREATE TABLE [dbo].[Sites](
 [SiteID] [int] IDENTITY(1,1) NOT NULL,
 [SiteInfo] [xml] NULL,
 [InVal] Varchar(50) NULL)
insert into [dbo].[Sites] ([InVal]) select 'ABC' union select 'DEF' union select 'GHI'
update [dbo].[Sites] SET [SiteInfo] = '<SiteInfo />'
update [dbo].[Sites] SET [SiteInfo].modify('insert <SiteID/> into (/SiteInfo[1])') 

Here is my update in it's most simple form.

update Sites SET [SiteInfo].modify('replace value of (/SiteInfo/@SiteID)[1] with sql:column("InVal")') 

I have tried with both singleton and non singleton nodes

The end result should preferably not be a singleton. i.e something like:

<SiteInfo>
 <SiteID>ABC</SiteID>
</SiteInfo>
asked May 13, 2018 at 21:53

1 Answer 1

3

You've got nothing to replace in <SiteID/>. Try and use an insert instead:

update Sites SET [SiteInfo].modify('insert text{sql:column("InVal")} as first into (/SiteInfo/SiteID)[1]');
answered May 13, 2018 at 22:41
3
  • Can you insert the node and text at the same time? Commented May 14, 2018 at 7:47
  • 1
    @Peter: Yes. update [dbo].[Sites] SET [SiteInfo].modify('insert <SiteID>123</SiteID> into (/SiteInfo[1])') Commented May 15, 2018 at 19:47
  • Eureka! update [dbo].[Sites] SET [SiteInfo].modify('insert <SiteID>text{sql:column("InVal")}</SiteID> into (/SiteInfo[1])') Commented May 16, 2018 at 1:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.