SQL Server – NTEXT Columns and String Manipulation

sql serversql-server-2008-r2string

I have a table with an NTEXT column called comments. I have a second string, let's call it anothercomment (a varchar) that needs placing inside a given comments string after the word UPDATEHERE.

Casting to nvarchar(max) truncates the comments string, so I cannot use the likes of CHARINDEX() (Msg 8152, Level 16, State 10, Line 2
String or binary data would be truncated.)
. I have used datalength() to check that there are a few thousand columns that are >8000 characters.

An example of what I want to achieve (albeit with much longer strings):

comments – This is a test UPDATEHERE This is the end of the test

anothercomment – . This is inserted.

Resulting string – This is a test UPDATEHERE. This is inserted. This is the end of the test

I realize that this is trivial with a normal varchar()/nvarchar(), but ntext is a complete and utter nightmare to work with. I realize it's a deprecated data type, but I did not write the application in question.

Best Answer

Converting to nvarchar(max) should work unless you are doing something wrong with your CHARINDEX()

Try this code snippet, it should output what you want.

-- Create the table
CREATE TABLE [dbo].[PhilsTable](
    [comment] [ntext] NULL,
    [anothercomment] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];

GO

-- insert very long string
INSERT INTO [dbo].[PhilsTable] (comment, anothercomment) VALUES (N'This is a test UPDATEHERE This is the end of the test' + REPLICATE (CAST(N'x' AS nvarchar(max)), 1000000), 'this goes in here');

-- verify data
SELECT DATALENGTH(comment), *  FROM [dbo].[PhilsTable];

-- perform replace
SELECT CAST(REPLACE(CAST(comment AS NVARCHAR(MAX)),'UPDATEHERE','UPDATEHERE' + anothercomment) AS NTEXT) FROM [dbo].[PhilsTable];

DROP TABLE [dbo].[PhilsTable];

Thanks go out to Andriy M for helping out with the REPLICATE statement.