Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace part of string in database

I need to replace all iframe tags, stored as nvarchar in my database. I can find the entries using the following sql-question:

SELECT * FROM databasename..VersionedFields WHERE Value LIKE '%<iframe%' 

Say I want to replace the following code segment:

code before iframe <iframe src="yadayada"> </iframe> code after iframe 

With this:

code before iframe <a>iframe src="yadayada"</a> code after iframe 
like image 697
Zooking Avatar asked Mar 03 '09 09:03

Zooking


People also ask

How do you replace part of a string?

The replace() method can take maximum of 3 parameters: old - old substring you want to replace. new - new substring which will replace the old substring. count (optional) - the number of times you want to replace the old substring with the new substring.

How do I remove a specific part of a string in SQL?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.


2 Answers

You can do it with an UPDATE statement setting the value with a REPLACE

UPDATE     Table SET     Column = Replace(Column, 'find value', 'replacement value') WHERE     xxx 

You will want to be extremely careful when doing this! I highly recommend doing a backup first.

like image 149
Mufaka Avatar answered Sep 18 '22 17:09

Mufaka


I think 2 update calls should do

update VersionedFields set Value = replace(value,'<iframe','<a><iframe')  update VersionedFields set Value = replace(value,'> </iframe>','</a>') 
like image 21
kristof Avatar answered Sep 20 '22 17:09

kristof