Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify sql server xml element name variable in xquery

Tags:

sql

xml

xquery

I need the name of the element is also a variable (is a parameter of the procedure)

Instead of this, which works fine:

DECLARE @VAR VARCHAR(5)
SET @VAR = 'false'
UPDATE CURVES
  SET CURVEENTITY.modify(
    'replace value of (/ElementName/text())[1] with  sql:variable("@VAR")') 
  WHERE ID = 3

But I would like something like this:

DECLARE @VAR VARCHAR(5)
DECLARE @VAR2 VARCHAR(20)
SET @VAR = 'false'
SET @VAR2 = 'ElementName'
UPDATE CURVES
  SET CURVEENTITY.modify(
    'replace value of (/sql:variable("@VAR2")/text())[1] with sql:variable("@VAR")') 
  WHERE ID = 3

But it does not work! How can I do this?

like image 308
evbell Avatar asked Jan 09 '14 02:01

evbell


People also ask

How edit XML in SQL?

Previously, a developer would update XML information by replacing the full XML document in the table column where it resided. But in the latest versions of SQL Server, we can use the XML modify() function in XQuery to update the XML data type column.

How do I declare a variable in XQuery?

declare variable $x := 7.5; declare variable $x as xs:integer := 7; Functions. “XQuery allows users to declare functions of their own. A function declaration specifies the name of the function, the names and datatypes of the parameters, and the datatype of the result.

What is XQuery used for in XML file?

XQuery is a functional language that is used to retrieve information stored in XML format. XQuery can be used on XML documents, relational databases containing data in XML formats, or XML Databases. XQuery 3.0 is a W3C recommendation from April 8, 2014.

Which XML data type methods are used with XQuery?

The query() Method This method basically needs an XPath expression in the XQuery parameter and returns an XML data type.


2 Answers

You can use local-name() in a predicate to find the node you want to modify.

declare @var2 varchar(50) = 'ElementName'
declare @var varchar(50) = 'false'

update CURVES
set CURVEENTITY.modify('replace value of ((*[local-name() = sql:variable("@var2")]/text())[1]) 
                        with sql:variable("@var")')
where ID = 3
like image 96
Mikael Eriksson Avatar answered Oct 19 '22 23:10

Mikael Eriksson


AFAIK you can't dynamically compose the path dynamically using a /sql:variable in xquery - you can build the path as a string and then use dynamic sql to execute it (in which case you may as well substitute both sql:variables).

e.g.

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'UPDATE CURVES
            SET CURVEENTITY.modify(''replace value of (/' + @var2 
                     + '/text())[1] with "' + @var + '"'') 
            WHERE ID = 3';
exec sp_executesql @sql;            

SQL Fiddle here

like image 20
StuartLC Avatar answered Oct 19 '22 23:10

StuartLC