tags:

views:

101

answers:

3

I'm tring to run a find and replace query on some sql data using Management Studio. I basically want to remove the word FREE from any content.

I tried running this query;

UPDATE    Table_1
SET              ContentDetails = REPLACE(ContentDetails, 'FREE', '')
WHERE     (ContentDetails LIKE '%FREE%')

But I get an error saying that data type text is invalid for argument 1 of replace function.

A: 

Try

UPDATE Table_1
SET    ContentDetails = REPLACE(CAST(ContentDetails as VARCHAR), 'FREE', '')
WHERE  (ContentDetails LIKE '%FREE%')

although it might cut the data off where the value is longer than what fits in a VARCHAR.

Vinko Vrsalovic
A: 

Updated due to comment

I think all you need to do is cast your ContentDetails field as a varchar with the length of the field i.e.

UPDATE Table_1
SET ContentDetails = REPLACE(CAST(ContentDetails as VARCHAR(100)), 'FREE', '')
WHERE ContentDetails LIKE '%FREE%'
James
The where condition is not futile, it will reduce the amount of updated rows, which can translate to a significant speed up
Vinko Vrsalovic
Ah ok never thought of it that way!
James
Thanks guys. Will this still work if the column is of type text?(Not sure why it was done as a text type originally.)
Neil Bradley
Any idea of how much of a speed up you get? Is it on the order of 10 percent? Or is it on the order of twice as fast, or better?
Walter Mitty
+1  A: 

Since you have a text column, you would need to use updatetext, which is painful, at best. However, you can cast contentdetails as a varchar(max), and you'll be peachy.

update table_1
set contentdetails = replace(cast(contentdetails as varchar(max)), 'FREE', '')
where contentdetails like '%FREE%'

Moreover, I highly recommend that you look into converting that column from text to varchar(max). It, along with ntext and image, is a currently deprecated data type, which will be removed at some point in the future of SQL Server.

Eric
Perfect. Thank you very much. We're looking at redeveloping the sites so that we can get rid of all of the bad design from previous developers. :)
Neil Bradley
Could this be modified just to find all instances within a particular table, rather than having to go through each column individually?
Neil Bradley
@Neil: Sorry, but no. I mean, you can create a script that will run through each column if you use `sp_executesql` and `sys.columns`, but there's no "replace everything in this database" command.
Eric