SQL 在数据库中搜索并替换部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/605768/
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
Search and replace part of string in database
提问by Zooking
I need to replace all iframe tags, stored as nvarchar in my database. I can find the entries using the following sql-question:
我需要替换所有以 nvarchar 形式存储在我的数据库中的 iframe 标签。我可以使用以下 sql 问题找到条目:
SELECT * FROM databasename..VersionedFields WHERE Value LIKE '%<iframe%'
Say I want to replace the following code segment:
假设我想替换以下代码段:
code before iframe <iframe src="yadayada"> </iframe> code after iframe
With this:
有了这个:
code before iframe <a>iframe src="yadayada"</a> code after iframe
回答by Mufaka
You can do it with an UPDATE statement setting the value with a REPLACE
您可以使用 UPDATE 语句使用 REPLACE 设置值来做到这一点
UPDATE
Table
SET
Column = Replace(Column, 'find value', 'replacement value')
WHERE
xxx
You will want to be extremely careful when doing this! I highly recommend doing a backup first.
执行此操作时您将需要非常小心!我强烈建议先进行备份。
回答by kristof
I think 2 update calls should do
我认为 2 个更新调用应该做
update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')
update VersionedFields
set Value = replace(value,'> </iframe>','</a>')
回答by Zooking
update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')
and you do it in a single pass.
你可以一次性完成。
回答by Westley
I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!
我刚刚面临类似的问题。我将 db 的内容导出到一个 sql 文件中,并使用 TextEdit 查找和替换我需要的所有内容。简单 ftw!
回答by Manu
I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.
我会考虑为这种字符串操作编写一个带有 RegEx 支持的 CLR 替换函数。
回答by Vijay Balkrishna konduskar
Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')
更新数据库并设置 fieldName=Replace (fieldName,'FindString','ReplaceString')