Wednesday, November 10, 2010

Replace a string in the mysql database using REPLACE function

Many times we have the need to change the values of database fields. If our table contains thousands of records, its not possible to manually edit the records. So we can use MySQL REPLACE function to replace the string. The syntax to use the replace function is as follows.


UPDATE `table_name` SET `field_name` = REPLACE(`field_name`, 'Keyword to be replaced', 'Replacement String');

For example if we have changed the website name , we also need to change the datas in the downloads table (if we have).


Now we can use a single sql query with REPLACE function , and it will affect the whole records.


UPDATE `tbl_downloads` SET `sitename` = REPLACE(`sitename`, 'www.old-sitename.com', 'www.new-sitename.com');

now all the datas with 'old-sitename' will replace with the new-sitename

No comments:

Post a Comment