简体   繁体   中英

Cannot call methods on varchar(max)

I tried to modify/update xml column of type varchar(max) in SQL Server.

But I'm getting this error:

Cannot call methods on varchar(max)

This is my table structure and query:

CREATE TABLE #Sites
(
    [SiteID] [INT] IDENTITY(1,1) NOT NULL,
    [SiteInfo] VARCHAR(MAX),
    [InVal] VARCHAR(50) NULL,
    [InVal1] VARCHAR(50) NULL
)

UPDATE #Sites 
SET [SiteInfo].modify('insert <SiteID/> into (/SiteInfo[1])') 

The only way you're going to be able to deal with this is to insert your data into an actual xml datatype in a (temporary) table, run an UPDATE on that and then UPDATE your original data. Provided that SiteID is unique then you can do something like this:

CREATE TABLE #Sites (id int IDENTITY(1,1),
                     NotXML varchar(MAX))
INSERT INTO #Sites (NotXML)
VALUES ('<SiteInfo><name>jagadish</name><state>NJ</state></SiteInfo>')
GO
CREATE TABLE #XML (id int,
                   RealXML xml);
INSERT INTO #XML
SELECT id, TRY_CONVERT(xml,NotXML)
FROM #Sites
WHERE id = 1
  AND TRY_CONVERT(xml,NotXML) IS NOT NULL; --as we can't deal with bad XML

UPDATE #XML
SET [RealXML].modify('insert <SiteID/> into (/SiteInfo[1])');

UPDATE S
SET NotXML = CONVERT(varchar(MAX),X.RealXML)
FROM #Sites S
     JOIN #XML X ON S.id = X.id;

SELECT NotXML
FROM #Sites;    

DROP TABLE #XML;
GO
DROP TABLE #Sites;

This, however, is going to be less than performant, and won't be able to handle bad XML; if your varchar(MAX) contains invalid XML it will not be updated.

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