0
votes

I'm trying to create a function able to rename an element within XML columns.

The function should be something as

create function dbo.fnRenameElement(
    @doc xml 
    , @parentElementPath nvarchar(MAX)
    , @oldElementName nvarchar (255)
    , @newElementName nvarchar (255)
    )
returns ... (whatever, not really interested actually)

Something I would use in this way

Select 
    dbo.fnRenameElement(MyTable.MyXmlColumn, 'some/xml/path/', 'ElementNameToReplace', 'NewElementName')
Where
    ...

I had a look at this answer, I have a similar need but I also need to have newName, OldName and xmlPath as variable, which I'm not able to work out.

It seems (am I wrong?) that I cannot use string variables withing query, modify, insert XQuery functions

I want to avoid any "convert to string - replace old with new element name - convert back to xml": this does not work if "oldElementName" can appear anywhere else within the xml column data

I'm afraid, that SQL-Server allows only for two options: 1) The ugly string-replace route and 2) dynamically created statements (which won't work within a function). You might read about XSLT...Shnugo
ouch! Not what I was hoping to read. I think I will try with dinamically created statements, within a SP. Or with a .Net app reading, modifiying and updading each xml.Gian Paolo