How To Use Replace function in TEXT and NTEXT fields

How To Use Replace function in TEXT and NTEXT fields

Replace function in T-SQL could be very useful. As its name implies, Replace function is used to search and replace some text. But, problem occurs if you try to use it with TEXTor NTEXT data types. In this case, SQL Server will return an error:

Error Message: Argument data type text is invalid for argument 1 or replace function.

This unfriendly message says that we have a problem, but doesn't say anything about how to solve it. Since Replace function is supported for VARCHAR and NVARCHAR data types, an easy solution is to convert TEXT or NTEXT data to VARCHAR and NVARCCHAR respectively.

Let say you have table Articles with column ArticleText which is of type NTEXT. Using of Replace function in example T-SQL code could look like this:

SELECT REPLACE(CAST(ArticleText AS NVARCHAR(MAX)),'Existing text','New text')
FROM Articles

This query is simply converted NTEXT data to NVARCHAR(MAX) and then used it in Replace function. Sometimes, you need to your query returns original data type. In this example, original data type is NTEXT. To get it back after replacing, we can use CAST function again. So, example would be a little bigger, like this:

SELECT CAST(REPLACE(CAST(ArticleText AS NVARCHAR(MAX)),'Existing text','New Text'AS NTEXT)
FROM Articles

T-SQL Replace function remarks

NVARCHAR(MAX), VARCHAR(MAX) and BINARY(MAX) are introduced with SQL Server 2005. They are created as replacement for TEXT, NTEXT and BINARY data types. As Microsoft said, TEXT, NTEXT and BINARY are obsolete and will be removed from future versions of SQL Server. Instead of using CAST function like in examples above, you can consider to redesign tables and change TEXT and NTEXT data types to new VARCHAR(MAX) and NVARCHAR(MAX).

Then you can use REPLACE or other function directly, without data conversion.

Also remember, there is always an option to do search/replace in application code by using C# or VB.NET

Happy coding!

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值