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?
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.
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.
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.
The query() Method This method basically needs an XPath expression in the XQuery parameter and returns an XML data type.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With