September 13, 2010 by Christoff Truter SQL
The modify method (when using the XML Type) allow developers
to update/insert/remove specific nodes within the XML field.
Lets have a quick look at how to use this method.
First of all we're going to create a little play table - a table containing
cars and a xml field containing the different colours we get for the car.
CREATE TABLE [dbo].[cars]( [carID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL, [title] [varchar](255) NOT NULL, [colours] [xml] NULL )
INSERT INTO cars(title, colours)
VALUES('VW', '<colours>
<colour>Red</colour>
</colours>')
UPDATE cars
SET colours.modify('insert element colour {"Green"}
as last
into (/colours)[1]')
WHERE carID = 1
UPDATE cars
SET colours.modify('insert element colour {"Lavendar"}
after (/colours/colour)[2]')
WHERE carID = 1
UPDATE cars
SET colours.modify('insert element colour {"Brown"}
after (/colours/colour[.="Green"])[1]')
WHERE carID = 1
UPDATE cars
SET colours.modify('insert
(
element colour {"Purple"},
element colour {"Pink"}
)
as last
into (/colours)[1]')
WHERE carID = 1
DECLARE @colours XML
SET @colours = '<colour>Orange</colour><colour>White</colour>'
UPDATE cars
SET colours.modify('insert
(
sql:variable("@colours")
)
as last
into (/colours)[1]')
WHERE carID = 1
UPDATE cars
SET colours.modify('replace value of (//colour[.="Green"])[1]
with "DarkGreen"')
WHERE carID = 1
UPDATE cars
SET colours.modify('delete (//colour[.="Blue"])')
WHERE carID = 1
UPDATE cars
SET colours.modify('delete (//colour[contains(.,"Green")])')
WHERE carID = 1