Let's say there is the following XML data and I want to add an attribute into salary like currency="INR"
:
<employee>
<salary amount="6000"/>
</employee>
If this data is stored in a column of type XML
, then another attribute is being added easily just by using this code snippet:
UPDATE TABLENAME SET COLUMNNAME.modify('insert attribute currency{"INR"} into (/employee/salary)[1]')
and if this data is stored in a column of type nvarchar(max)
, then the following query is not working even after casting the data as xml
:
UPDATE TABLENAME SET CAST(CAST(COLUMNNAME AS VARCHAR(MAX)) AS XML).modify('insert attribute currency{"INR"} into (/employee/salary)[1]')
So, help me to resolve second point as I have a column as nvarchar and I need to insert an attribute into saved xml data.
modify() Method
works only with variable/column directly and can only used in the SET
clause.
So, to solve this since you are storing your data as NVARCHAR
, you have two choices:
Alter your table and add a new column with XML
datatype, move the data to it from your column, and then UPDATE
the data using modify()
Create/declare a table to store your data as XML
and do the UPDATE
.
Here is an example for what you provide:
CREATE TABLE T
(
Value NVARCHAR(MAX)
);
INSERT INTO T
SELECT N'<employee>
<salary amount="6000"/>
</employee>';
DECLARE @V XML;
SELECT @V = CAST(Value AS XML)
FROM T;
SET @V.modify('insert attribute currency{"INR"} into (/employee/salary)[1]');
UPDATE T
SET Value = CAST(@V AS NVARCHAR(MAX));
SELECT * FROM T;
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.