Pages

Social Icons

Wednesday 11 December 2013

SQL-Server: modify, exist in xml

Hi,
In sql-server we have modify,exist and delete functions to change the xml data. Below is the example of replacing the xml value when it is having some specified value.

Example: I want to change the Node A value only when it is having 1 as a value 


declare @tbl table(col xml)

declare @sql xml ='<SomeNode><A>1</A><B>1</B></SomeNode><SomeNode><A /><B /></SomeNode><SomeNode><A /><B /></SomeNode>'

insert into @tbl
select @sql

select * from @tbl

update @tbl
set    col.modify('replace value of (/SomeNode/A[. = "1"]/text())[1] 
                       with ""')
where  col.exist('/SomeNode[A = "1"]') = 1 and
       col.exist('/SomeNode[A = "1"]') = 1


select * from @tbl

Thx,
RS
11/12/13