开发者

SQL Query Replace All

I want to modify the following query:

UPDATE wp_posts
SET post_content =
      REPLACE(post_content, 'http://oldlink.com', 'http://newlink.com');

To be something that goes through all tables, columns and values. Something similar to this (but this doesn't work):

UPDATE * SET *= REPLACE(*, 'http://oldlink.com', 'http://newlink.com'); 

I want to replace every instance of my old link to my new link in my database. Is there any way to do this?

UPDATE

Sorry, I forgot to mention, it's MySQL. I'm currently going through all the answers and I'll be back and let you know what worke开发者_开发百科d. Thanks everyone!

UPDATE 2

Hi guys (and girls), I decided to just dump the database and do manual search and replace (with TextWrangler). As this isn't (currently) a large DB, it's probably the easiest way.


Here is one that works on SQL Server -- does something like this work for you?

Search and Replace SQL Server data in all columns, of all tables

Here's a stored procedure named, SearchAndReplace, that searches through all the character columns of all tables in the current database, and replaces the given string with another user provided string.


This mssql script will whine a bit if there is a computed column in a table, but it will still execute:

DECLARE @searchvalue varchar(100)
DECLARE @newvalue varchar(100)
SET nocount off

SET @searchvalue = 'http://oldlink.com'
SET @newvalue = 'http://newlink.com'

SELECT * into #t FROM 
(
SELECT 'update [' + a.TABLE_name + '] SET ['+ column_name+ ']=''' + @newvalue + '''
where [' +a.column_name+
']='''+@searchvalue +'''' sqlstring
FROM INFORMATION_SCHEMA.COLUMNS a
join 
INFORMATION_SCHEMA.TABLES b
ON a.TABLE_name = b.TABLE_name
and b.TABLE_type = 'base table'
WHERE data_type in ('varchar', 'char', 'nvarchar')
and character_maximum_length >= len(@newvalue)
) a

DECLARE @sqlstring as nvarchar(500)
DECLARE SqlCursor CURSOR FAST_FORWARD FOR
SELECT sqlstring FROM #t
OPEN SqlCursor
FETCH NEXT FROM SqlCursor
INTO @sqlstring
WHILE @@FETCH_STATUS = 0
BEGIN

     EXEC(@sqlstring)
     FETCH NEXT FROM SqlCursor
     INTO @sqlstring
END
CLOSE SqlCursor
DEALLOCATE SqlCursor
DROP TABLE #t


You didn't mention the database. I currently use Sybase ASA, where you cannot do this literally but it can be done by checking the column names from a join of systable and syscolumn and then using execute immediate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜