简体   繁体   中英

SQL Update XML Value stored in ntext colum

I need to update two values within XML data that is stored in a ntext column. I have a copy of the database to test with, and I haven't been successful with the information I have found.

Here is a sample the XML that I need to update:

<?xml version="1.0" encoding="utf-16"?>
<cmnReportExportParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DSNs>
    <ReportDSN>
       <Name>Name</Name>
       <Database>DBName</Database>
       <Server />
       <User>user</User>
       <Password>removed </Password>
      <DevelopmentName>DBName</DevelopmentName>
    </ReportDSN>
  </DSNs>
</cmnReportExportParameters>

I need to update the "user" and "password" fields within this XML data. This is part of a legacy CMS application, and I am simply supporting the system (I'm not the developer).

I can cast the data successfully select Name, Parameters, CAST(parameters as xml) from tablename

Any guidance is appreciated.

This is far from ideal, but this is the only way I can think to do it. As your column is the wrong data type ( ntext ) you can't use the modify XQUERY command. Thus, you have to insert your data into a temporary table, update it, and then reinsert it. This is not going to be great for performance, but it works. As I said before, fixing the data type will make this far easier:

CREATE TABLE [sample] (YourIDCol int IDENTITY(1,1),
                       NotXML ntext);
INSERT INTO [sample] (NotXML)
VALUES (
N'<?xml version="1.0" encoding="utf-16"?>
<cmnReportExportParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DSNs>
    <ReportDSN>
       <Name>Name</Name>
       <Database>DBName</Database>
       <Server />
       <User>user</User>
       <Password>removed </Password>
      <DevelopmentName>DBName</DevelopmentName>
    </ReportDSN>
  </DSNs>
</cmnReportExportParameters>');
GO
CREATE TABLE #UpdateXML (ID int, ActualXML xml);
INSERT INTO #UpdateXML (ID,ActualXML)

SELECT YourIDCol,
       TRY_CONVERT(xml,NotXML)
FROM [sample]
WHERE TRY_CONVERT(xml,NotXML) IS NOT NULL
  AND YourIDCol = 1; --if you need it

UPDATE #UpdateXML
SET ActualXML.modify('replace value of (cmnReportExportParameters/DSNs/ReportDSN/User/text())[1] with ("NewUsername")');

UPDATE #UpdateXML
SET ActualXML.modify('replace value of (cmnReportExportParameters/DSNs/ReportDSN/Password/text())[1] with ("NewPassword")');

UPDATE S
SET NotXML = CONVERT(ntext,CONVERT(nvarchar(MAX),U.ActualXML)) --yuck
FROM [sample] S
     JOIN #UpdateXML U ON S.YourIDCol = U.ID;

SELECT *
FROM [sample];

DROP TABLE #UpdateXML;
GO

DROP TABLE [sample];

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