SQL Server Update the Xml value in a SQL table

3mpgtkmj  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(101)

In SQL I have no experience with XML columns and values.

I need to update (with a SQL query) the

<row note="49"> deadline detail</row>

to read:

<row note="49"> Deadline Balance</row>

There are multiple notes with different ids, in my case I only have to modify the one with id 49.

The structure of the column is this:

<rows>
   <row nota="2">Contratto depositato [...] :-) </row>
   <row nota="3">
       Gli è stata concessa una dilazione.
       Porre attenzione alle condizioni.
    </row>
    <row nota="49">deadline details</row>
</rows>

I tried this :

UPDATE CF 
SET NoteXML.modify('replace value of (/rows/row[@nota="49"]/text())[1] with "deadline detail"')
WHERE Cd_CF = 'C000001'

And this is the error I get:

XQuery [CF.NoteXML.modify()]: The operator could not be applied "=" to the operands "xs:unsignedInt" and "xs:string".

ztigrdn8

ztigrdn81#

It seems to be working.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Cd_CF VARCHAR(10), NoteXML XML);
INSERT @tbl (Cd_CF, NoteXML) VALUES
('C000001', N'<rows>
   <row nota="2">Contratto depositato [...] :-) </row>
   <row nota="3">
       Gli è stata concessa una dilazione.
       Porre attenzione alle condizioni.
    </row>
    <row nota="49">deadline details</row>
</rows>');
-- DDL and sample data population, end

DECLARE @replaceWith VARCHAR(30) = 'Deadline Balance';

-- before
SELECT * FROM @tbl;

UPDATE @tbl 
SET NoteXML.modify('replace value of (/rows/row[@nota="49"]/text())[1] with sql:variable("@replaceWith")')
WHERE Cd_CF = 'C000001';

-- after
SELECT * FROM @tbl;

Output

<rows>
  <row nota="2">Contratto depositato [...] :-) </row>
  <row nota="3">
       Gli è stata concessa una dilazione.
       Porre attenzione alle condizioni.
    </row>
  <row nota="49">Deadline Balance</row>
</rows>
ibrsph3r

ibrsph3r2#

You can cast the @nota attribute to an integer in your XQuery expression. Here's the modified query:

UPDATE CF
SET NoteXML.modify('replace value of (/rows/row[@nota=49]/text())[1] with "Deadline Balance"')
WHERE Cd_CF = 'C000001'

Or else you can explicitly cast the @nota to a string by using below query

UPDATE CF
SET NoteXML.modify('replace value of (/rows/row[@nota = string("49")]/text())[1] with "Deadline Balance"')
WHERE Cd_CF = 'C000001'

相关问题