Search and replace part of string in database

2019-01-13 09:27发布

问题:

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

回答1:

I think 2 update calls should do

update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')

update VersionedFields
set Value = replace(value,'> </iframe>','</a>')


回答2:

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.



回答3:

update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')

and you do it in a single pass.



回答4:

I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!



回答5:

I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.



回答6:

Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')