The ability to search for and replace a substring of text is such a useful, and often necessary, bit of functionality that nearly every text editor on the planet has it built in. However, the tool we often use to hold our text based data, the ubiquitous relational database, typically has very poor support for doing search and replace out of the box.
Its so poor in fact that I’ve actually discussed this very topic, Search & Replace for your Database, before! However, as was noted in the comments to that post, my solution hack is not 100% effective. Actually, in practice I’ve found it to be quite broken. :(
A better way to replace text
As part of my search for a better way to do the database search and replace I went to my new human-powered-answer-finding-machine, Twitter! I asked my Twitter friends
Does anyone know of a tool that allows me to do a find and replace within a given column and table of a database?
Naturally I got a few smart-ass answers back... but what else would I expect. I mean these guys wouldn’t be my friends if they too weren’t snarky know-it-alls. :) Anyhow, Kevin Dente suggested taking advantage of SQL Server’s build in Replace function.
For some reason I knew I’d tried that before and it didn’t work. But I figured what the hell and gave it another shot. Surprise, surprise... it still didn’t work and SQL Server complained that
Msg 8116, Level 16, State 1
Argument data type ntext is invalid for argument 1 of replace function.
ntext... doh!
See, I knew there was a reason it didn’t work the last time I tried that... in this particular case I’m working with a ntext datatype column. So Kevin’s suggestion was perfectly valid and would have worked just fine for a binary or character (char, varchar, nvarchar, etc...) based column.
But wait... why not just cast my ntext data to an nvarchar?
Just fake it
I tried casting my ntext data to nvarchar data and to my surprise it worked! Here’s an example where I’m searching the myTable.myColumn column for the string "rob conery" and it will be replaced with "jon galloway".
UPDATE myTable
SET myColumn = Replace(Cast(myColumn AS NVARCHAR(Max)),
'rob conery',
'jon galloway')
No don’t everyone go out and start replacing Rob with Jon. :)