简体   繁体   English

SQL Server 在 TEXT 字段中查找和替换

[英]SQL Server find and replace in TEXT field

I have a database in SQL Server 2005 that was brought up from SQL Server 2000 and is still using TEXT type fields instead of varchar(max).我在 SQL Server 2005 中有一个数据库,它是从 SQL Server 2000 中创建的,并且仍在使用 TEXT 类型的字段而不是 varchar(max)。

I need to find and replace a string of characters in the text field but all of the examples of how to do this that I have found don't seem like they would work for me.我需要在文本字段中查找并替换一串字符,但我发现的所有如何执行此操作的示例似乎都不适合我。 It seems the UPDATETEXT command requires that the two parameters "insert_offset" and "delete_length" be set explicitly but the string i am searching for could show up in the text at any point or even at several points in the same cell.似乎 UPDATETEXT 命令要求明确设置两个参数“insert_offset”和“delete_length”,但我正在搜索的字符串可能会出现在文本中的任何点,甚至是同一单元格中的多个点。 My understanding of these two parameters is that the string im searching for will always be in the same place, so that insert_offset is the number of spaces into the text that the UPDATETEXT command will start replacing text.我对这两个参数的理解是 im 搜索的字符串将始终位于同一位置,因此 insert_offset 是 UPDATETEXT 命令将开始替换文本的文本中的空格数。

Example: Need to find: &lt;u&gt;示例:需要找到: &lt;u&gt; and Replace it with: <u>并将其替换为: <u>

Text field example:文本字段示例:

*Everyone in the room was <b>&lt;u&gt;tired&lt;/u&gt;.</b><br>Then they woke <b>&lt;u&gt;up&lt;/u&gt;.

Can anyone help me out with this?谁能帮我解决这个问题? THANKS!谢谢!

I finally figured it out.我终于弄明白了。 It was buried in the comments to the article jfrobishow published.它被隐藏在对 jfrobishow 发表的文章的评论中。 Thank you SO much.太感谢了。

Here is the whole response that led me to the solution:这是使我找到解决方案的整个响应:

quote:Originally posted by fredclown引用:最初由 fredclown 发表

If you use SQL 2005 you can use replace with a text type.如果您使用 SQL 2005,则可以使用文本类型替换。 All you have to do is the below ...您所要做的就是以下...

field = replace(cast(field as varchar(max)),'string' ,'replacement') field = replace(cast(field as varchar(max)),'string','replacement')

Easy as pie.非常简单。

Two thumbs up to Fredclown!!!向弗雷德克伦竖起两个大拇指!!! command work like a charm for me as well.命令对我来说也是一种魅力。 This is what I wrote my Update statement to Find and Replace in a Text field in SQL server 2005 database这就是我在 SQL server 2005 数据库中的文本字段中编写更新语句以查找和替换的内容

UPDATE TableName SET DBTextField = REPLACE(CAST(DBTextField AS varchar(MAX))
                                               ,'SearchText', 'ReplaceText')
FROM TableName
WHERE CHARINDEX('SearchText',CAST(DBTextField as varchar(MAX)))>0

Note:that this may truncate the size of you dbfield , but if is a long text column make it nvarchar(max) and you should not get none truncation!注意:这可能会截断您 dbfield 的大小,但如果是一个长文本列,请将其设为nvarchar(max)并且您不应得到任何截断!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM