Sunday, February 15, 2009

[T-SQL] How to REPLACE on TEXT field

The REPLACE T-SQL function can be used only with VARCHAR - if you try to run REPLACE on a TEXT field you'll notice you're pretty much screwed (and that's probably how you ended up on this page in the first place).

There are ridiculously complicated ways to overcome this but the easieast solution I was able to find around is the following:

UPDATE myTable
SET myField = REPLACE(SUBSTRING(myField, 1, DATALENGTH(myField)), 'string2replace', 'replacementString')

SUBSTRING is returning VARCHAR so this way it works like charme.

I HATE SQL but I am getting to know more than I would like about it.

UPDATE:
as pointed out by people in the comments, the above will truncate to 8000 characters. This wasn't a concern for me at all because I knew my strings where pretty short. If you're worried about truncation you can use a CAST (check comments for more details).

kick it on DotNetKicks.com

12 comments:

CorinaCorina said...

Fantastic...Thanks so much. This worked like a charm.

Anonymous said...

It seems to truncate the text to 8000 characters

Unknown said...

I believe SUBSTRING converts to varchar(max) which is indeed 8000 ... :0

Anonymous said...

You can use the CAST keyword to cast the text field to Varchar(8000) for instance like so:

CAST(myfield AS Varchar(8000)

Alan S said...

Excellent! I was headed down that ridiculously complicated path. You saved me serious time.

Muron said...

Handy trick saved me a bunch of time.

Unknown said...

Nice one - better than the 50 line alternatives online!

Iatek said...

Thanks -- you saved me a lot of time on this.

Mutuelle sante said...

Incredibly complete and extremely good advices on how to replace on text field.Thanks and great job

Anonymous said...

Thanks...you saved my hours...

Anonymous said...

Are you guys serious? This will truncate your text if it's longer than 8000 characters!

Anonymous said...

Using SUBSTRING( myField, 1, DATALENGTH(myField)) will truncate to 8000 chars. If you use CAST( myField as varchar(max)) it does not.