SQL 在 text 或 ntext 数据类型上替代 REPLACE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4341613/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 08:27:12  来源:igfitidea点击:

alternatives to REPLACE on a text or ntext datatype

sqlsql-servertsql

提问by ethem

I need to update/replace the data in datatable.column. The table has a field named Content. I'm using the REPLACEfunction. Since the column datatype is NTEXT, SQL Server doesn't allow me to use the REPLACEfunction.

我需要更新/替换 datatable.column 中的数据。该表有一个名为 的字段Content。我正在使用该REPLACE功能。由于列数据类型是NTEXT,SQL Server 不允许我使用该REPLACE函数。

I can't change the datatype because this database is 3rd party software table. Changing the datatype will cause the application to fail.

我无法更改数据类型,因为此数据库是 3rd 方软件表。更改数据类型将导致应用程序失败。

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = REPLACE(Content,'ABC','DEF') 
WHERE Content LIKE '%ABC%' 

I Receive this error:

我收到此错误:

Msg 8116, Level 16, State 1, Line 1 Argument data type ntext is invalid for argument 1 of replace function.

消息 8116,级别 16,状态 1,第 1 行 参数数据类型 ntext 对替换函数的参数 1 无效。

  • Can I fix this with T-SQL? Does someone have an example how to read and to loop?
  • Since this is onetime conversion, maybe I can change to another type but I'm afraid I'm messing up the data.
  • 我可以用 T-SQL 解决这个问题吗?有人有如何阅读和循环的例子吗?
  • 由于这是一次性转换,也许我可以更改为另一种类型,但我担心我会弄乱数据。

There is a primary key field: name: ID - integer - it's an identity.... So I need to think about this too. Maybe set the Identity to N temporary.

有一个主键字段:名称:ID - 整数 - 它是一个身份......所以我也需要考虑这一点。也许将 Identity 设置为 N 临时。

Please advise on how to achieve the REPLACE function?

请教如何实现REPLACE功能?

Approx. 3000 statements need to be updated with a new solution.

大约 3000 条语句需要使用新解决方案进行更新。

回答by p.campbell

IFyour data won't overflow 4000 characters ANDyou're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

如果您的数据不会溢出 4000 个字符并且您使用的是 SQL Server 2000 或兼容级别为 8 或 SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

对于 SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

回答by LittleBobbyTables - Au Revtheitroad

Assuming SQL Server 2000, the following StackOverflow questionshould address your problem.

假设 SQL Server 2000,以下StackOverflow 问题应该可以解决您的问题。

If using SQL Server 2005/2008, you can use the following code (taken from here):

如果使用 SQL Server 2005/2008,则可以使用以下代码(取自此处):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable