1

My first question on Stack Overflow :)

I have XML:

DECLARE @xml XML = '<root><tag1 /><tag2 /></root>';

I need to remove node, but, path to node is variable "@path".

DECLARE @path XML = '/root/tag2';

My query is:

SET @xml.[modify]('delete sql:variable("@path")');

But, I get error: Msg 9342, Level 16, State 1, Line 9 XQuery [modify()]: An XML instance is only supported as the direct source of an insert using sql:column/sql:variable.

So my question is: how can I delete xml node by sql parameter?

2
  • You cannot use a variable for the XPath, but you can use various predicates. Please provide more information about your real-world-needs... Just to mention: There is a way via dynamically created SQL and EXEC()... Commented Feb 23, 2017 at 10:09
  • Its complex to describe, just created simplified example. I have more requirements here: one is to keep same session. So, dynamic sql is last option to use. Thanks for your answer. Commented Feb 23, 2017 at 10:16

1 Answer 1

6

There is no general recipie...

Just some ideas:

If you know the node's name

DECLARE @xml XML = '<root><tag1 /><tag2 /></root>';
DECLARE @nodeToDelete VARCHAR(100)='tag2';
SET @xml.modify('delete (/root/*[local-name()=sql:variable("@nodeToDelete")])[1]');
SELECT @xml;

If you know the node's name with FLWOR-query

DECLARE @xml XML = '<root><tag1 /><tag2 /></root>';
DECLARE @nodeToDelete VARCHAR(100)='tag2';
SET @[email protected]('<root>
                     {
                     for $nd in /root/*[local-name()!=sql:variable("@nodeToDelete")]
                       return $nd
                     }
                     </root>');
SELECT @xml;

dynamically created

DECLARE @xpath VARCHAR(100)='/root/tag2';

DECLARE @command VARCHAR(MAX)=
'DECLARE @xml XML = ''<root><tag1 /><tag2 /></root>'';
 SELECT @xml;
 SET @xml.modify(''delete ' +  @xpath + ''');
 SELECT @xml';

PRINT @command;
EXEC(@command);
Sign up to request clarification or add additional context in comments.

1 Comment

At last, I used dynamic way. Thanks.

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.