modify(replace) XML for conditions

前端 未结 1 1534
离开以前
离开以前 2020-12-20 04:02

I want to replace the value in an element tag, depending on its value, as well as the value of another element(in the same level as said element), both elements being inside

相关标签:
1条回答
  • 2020-12-20 04:43

    it's not possible to replace multiple values at once in xml in SQL Server, there're a several options:

    • use loop and update attributes one by one
    • split data into temporary table/table variable, update and then merge into one xml
    • use xquery to rebuild xml

    I think correct way for you would be loop solution:

    select @i = @data.value('count(//Attribute[DataType="Float" and Format="n0"]/Format)', 'int')
    
    while @i > 0
    begin
        set @data.modify('
             replace value of
                 (//Attribute[DataType="Float" and Format="n0"]/Format/text())[1]
             with "f2"
        ')
    
        set @i = @i - 1
    end
    

    sql fiddle demo


    If your xml contains namepaces, simplest way to update I found would be to declare default namespace:

    ;with xmlnamespaces(default 'schemas.microsoft.com/sqlserver/2004/10/semanticmodeling')
    select @i = @xml.value('count(//Attribute[DataType="Float" and Format="n0"]/Format)', 'int')
    
    while @i > 0
    begin
        set @xml.modify('
             declare default element namespace "schemas.microsoft.com/sqlserver/2004/10/semanticmodeling";
             replace value of
                 (//Attribute[DataType="Float" and Format="n0"]/Format/text())[1]
             with "f2"
        ')
    
        set @i = @i - 1
    end
    select @xml
    
    0 讨论(0)
提交回复
热议问题