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

后端 未结 3 549
忘了有多久
忘了有多久 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:27
    update my_table
    set xml_column = replace(xml_column, "old  value", "new value")
    
    0 讨论(0)
  • 2020-12-24 08:33

    To find a content in an XML column, look into the exist() method, as described in MSDN here.

    SELECT * FROM Table
    WHERE XMLColumn.exist('/Root/MyElement') = 1
    

    ...to replace, use the modify() method, as described here.

    SET XMLColumn.modify('
      replace value of (/Root/MyElement/text())[1]
      with "new value"
    ')
    

    ..all assuming SqlServer 2005 or 2008. This is based on XPath, which you'll need to know.

    0 讨论(0)
  • 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) )

    0 讨论(0)
提交回复
热议问题