我可以在 t-sql 中进行查找/替换吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/171412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I do a find/replace in t-sql?
提问by Joel Martinez
I basically have an xml column, and I need to find and replace one tag value in each record.
我基本上有一个 xml 列,我需要在每条记录中查找并替换一个标记值。
回答by Cory Mawhorter
For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution:
对于任何真实的事情,我会使用 xpaths,但有时您只需要一个快速而肮脏的解决方案:
You can use CAST to turn that xml column into a regular varchar, and then do your normal replace.
您可以使用 CAST 将该 xml 列转换为常规 varchar,然后进行正常替换。
UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[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.
当您只需要运行快速查询来查找某些内容,而不想处理 xpath 时,同样的技术也使搜索 XML 变得轻而易举。
SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%'
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.
编辑:只是想稍微更新一下,如果您收到一条类似于将一个或多个字符从 XML 转换为不可能的目标排序规则的消息,那么您只需要使用支持 unicode 的 nvarchar。
CAST( xmlCol as nvarchar(max) )
CAST( xmlCol as nvarchar(max) )
回答by Michael Petrotta
To find a content in an XML column, look into the exist() method, as described in MSDN here.
要在 XML 列中查找内容,请查看exist() 方法,如 MSDN此处 中所述。
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.
..所有假设 SqlServer 2005 或 2008。这是基于 XPath,你需要知道。
回答by Avdi
update my_table
set xml_column = replace(xml_column, "old value", "new value")