Can I do a find/replace in t-sql?

后端 未结 3 693
忘了有多久
忘了有多久 2020-12-24 08:24

I basically have an xml column, and I need to find and replace one tag value in each record.

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 08:36

    For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution:

    You can use CAST to turn that xml column into a regular varchar, and then do your normal replace.

    UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]')

    That same technique also makes searching XML a snap when you need to just run a quick query to find something, and don't want to deal with xpaths.

    SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%'

    Edit: Just want to update this a bit, if you get a message along the lines of Conversion of one or more characters from XML to target collation impossible, then you only need to use nvarchar which supports unicode.

    CAST( xmlCol as nvarchar(max) )

提交回复
热议问题