Sql Xquery How to Replace text in Update Query

前端 未结 1 788
北恋
北恋 2021-02-14 07:00

Table is named as MasterTable

Columns

ID type BIGINT,

Name type VARCHAR(200) (stores

相关标签:
1条回答
  • 2021-02-14 08:00

    You can not assign from a xml.modify. Modify works on the variable/column directly. You can also not use modify on a cast.

    You can extract the name to a xml variable, modify the xml and then put it back to the table.

    declare @str varchar(200) = 'Test'
    declare @xml xml
    
    select @xml = cast(Name as xml)
    from MasterTable
    where ID = 18
    
    set @xml.modify('replace value of (en-US/text())[1] with sql:variable("@Str")')
    
    update MasterTable
    set Name = cast(@xml as varchar(200))
    where ID = 18
    

    If you need this to work over more than one row at a time you can use a table variable with columns id and name where data type for name is xml instead of the @xml variable.

    declare @str varchar(200) = 'Test Text'
    declare @T table (ID int, Name xml)
    
    insert into @T
    select ID, cast(Name as xml)
    from MasterTable
    where Name is not null
    
    update @T
    set Name.modify('replace value of (en-US/text())[1] with sql:variable("@Str")')
    
    update MasterTable
    set Name = cast(T.Name as varchar(200))
    from @T as T
    where MasterTable.ID = T.ID
    
    0 讨论(0)
提交回复
热议问题