简体   繁体   中英

Update Inner text value of XML node with temp variable in SQL Server

<metadata>
  <layout>8</layout>
  <maxScore>7</maxScore>
</metadata>

I do want to replace value of <maxscore> for multiple records in a table whose column is XML type. And <maxscore> replace value is received in a temp variable as @MaxReplace.

Tried as below.

DECLARE @MaxReplace as NVARCHAR(10)
SET @MaxReplace='1'     
Update dbo.SCORETBALE
SET [XML].modify('replace value of (/ns:metadata/ns:maxScore)[1] with "@MaxReplace "')
  FROM  dbo.XYZ...(condition)... 

You need to select element first and bind value from variable using sql:variable(...) :

CREATE TABLE #SCORETBALE(col XML);

INSERT INTO #SCORETBALE(coL)
VALUES ('<metadata>
  <layout>8</layout>
  <maxScore>1</maxScore>
  </metadata>');

DECLARE @MaxReplace AS NVARCHAR(10) = '22';

UPDATE #SCORETBALE
SET col.modify('replace value of (/metadata/maxScore/text())[1] 
                with sql:variable("@MaxReplace")')
-- WHERE ...

SELECT *
FROM #SCORETBALE;

LiveDemo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM