Reputation: 73
I have a stored SQL procedure, which has declared xml variable with this kind of structure
<a>
<b>4</b>
<b>18</b>
<b>2</b>
</a>
I need to do something like UPDATE a SET b=b-1 WHERE b>@MyIntVariable
for this XML data. What is the best way to do it in MS Transact SQL?
Upvotes: 2
Views: 2021
Reputation: 1624
The modify function would be the most appropriate for manipulating xml data. See http://msdn.microsoft.com/en-us/library/ms190675(v=sql.105).aspx.
DECLARE @NUM INT = 10
DECLARE @xml XML = N'
<a>
<b>4</b>
<b>18</b>
<b>2</b>
</a>
';
SELECT @XML;
DECLARE @COUNT INT
SET @COUNT = @XML.value ('count(/a/b)', 'int');
WHILE @COUNT > 0
BEGIN
SET @XML.modify('replace value of (/a/b[sql:variable("@COUNT")]/text())[1] with
(
if ((/a/b[sql:variable("@COUNT")])[1] > sql:variable("@NUM")) then
(/a/b[sql:variable("@COUNT")])[1] - 1
else
(/a/b[sql:variable("@COUNT")])[1] cast as xs:double ?
)
')
SET @COUNT = @COUNT - 1;
END
SELECT @XML
Upvotes: 3