Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace in SQL UPDATE?

Tags:

string

sql

mysql

Here's a sample table:

name       |   picture  John S.    |   http://servera.host.com/johns.png Linda B.   |   http://servera.host.com/lindab.png ... 

Let's say there are several hundred more records.

Let's also say we moved servers from "servera" to "serverb".

Would it be possible to go into this table with one query to rename the content in the column "picture" for every record to read the correct server name?

like image 454
Julian H. Lam Avatar asked Oct 15 '10 16:10

Julian H. Lam


People also ask

Can we use Replace function in update statement in SQL?

You can use REPLACE in an UPDATE statement.

What are the 3 update commands in SQL?

Data modification side of DML language in T-SQL includes three statements used for modifying data in SQL Server and those are: INSERT, UPDATE, and DELETE.

How do you change a string value in SQL?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.


2 Answers

T-SQL:

update TBL     set picture = Replace(picture, 'servera', 'serverb')   where picture like '%servera%' 

Oracle:

update TBL     set picture = replace(picture, 'servera', 'serverb')   where picture like '%servera%' 

MySQL:

update TBL     set picture = REPLACE(picture, 'servera', 'serverb')   where picture like '%servera%' 
like image 193
Anatoly G Avatar answered Sep 22 '22 02:09

Anatoly G


UPDATE users SET picture = REPLACE(picture, 'http://servera.host.com/', 'http://serverb.host.com/') WHERE picture LIKE 'http://servera.host.com/%'; 

I'm including more of the string because I'd worry about 'fixing' an image named 'somethingserverasomething.jpg'. I might also think about having a base_url table and just storing image file names in users, but that's not the question you asked ;-)

like image 36
Andrew Avatar answered Sep 23 '22 02:09

Andrew