Replacing a string using SQL Server Replace function - string has more than 4000 characters - what to do?

感情迁移 提交于 2021-02-10 13:45:12

问题


I have a table, where I need to replace some values in a column.

The database is running on SQL Server 2005.

The problem is that some of the rows contain more than 4000 characters, which is giving the REPLACE function some trouble, since it demands that I cast the first parameter to the datatype NVARCHAR, and therefore any characters exceeding 4000, is being truncated.

Is there any workaround for this, other than writing an application that handles this issue?

The query in question is:

SELECT 
   Replace(cast([Database].[dbo].[fruits].[Tekst] as NVARCHAR(MAX)), 'bananas', 'apples') 
FROM [Database].[dbo].[fruits]

The column fruits is of datatype Text

Any input appreciated.


回答1:


I suspect that you have just hit the limit for an individual value in SSMS.

Annoyingly it doesn't allow you to set this to be unlimited and the only way I know of displaying long text is via casting to XML as below.

select
(select Replace(cast([Database].[dbo].[fruits].[Tekst] as NVARCHAR(MAX)),'bananas','apples')  AS [processing-instruction(x)] FOR XML PATH(''), TYPE)
FROM [Database].[dbo].[fruits]



回答2:


This demonstrates how REPLACE can handle longer string

SELECT CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000)

SELECT LEN(
       CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000)
       ) --11997

SELECT REPLACE(CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000), 'def', 'ddeeff')

SELECT LEN(
       REPLACE(CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000), 'def', 'ddeeff')
       ) --15996


来源:https://stackoverflow.com/questions/5245721/replacing-a-string-using-sql-server-replace-function-string-has-more-than-4000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!