I have a SQL Server XML column with data like this:
<History>
<Entry>
.....
</Entry>
<Entry>
.....
</Entry>
</History>
I need to add a unique identifier to each Entry element, giving this result:
<History>
<Entry entryID="AAA">
.....
</Entry>
<Entry entryID="BBB">
.....
</Entry>
</History>
I have it working for the first occurrence of the Entry element but don't know how to apply it to all occurrences. Also, this entryID is a GUID and I don't know how to generate a new one for each row.
Here is how I update the first element.
declare @eventId varchar(64)
set @eventId = CONVERT(varchar(64),NEWID())
update Histories
set XmlHistory.modify('
insert attribute EntryID {sql:variable("@eventId")}
into (History/Entry)[1]
')
where HistoryID=285162
I also have query that selects the elements that need this attribute and do not already have it. This gives the primary key and the element I need to update. I can't get a unique element identifier to use for the element array index.
select h.id rowPK, m.c.query('.') theElement
from TheTable h
cross apply h.XMLColumn.nodes('History/Entry[not(@EntryID)]') m(c)
where XMLColumn.exist('(History/Entry)')= 1