1

I have a table which references mobile numbers, but they are not all in international format. In the mobile column, I have many records and I need to change just all records with a 1 as first char to 491 and leave the rest unchanged. I tried this:

UPDATE test
SET mobile=(REPLACE (mobile,'1','491'));

But it turns a number like 1512231178 to 4915122349149178. It should be 491512231178. I think I need something like REGEXP '^1' in the REPLACE.

How can I do this with a simple update?

1
  • MariaDB's REGEXP_REPLACE() Commented Jun 27, 2015 at 1:41

2 Answers 2

3

You can simply do like this:

UPDATE test SET mobile = '49' + mobile
where mobile like '1%'
Sign up to request clarification or add additional context in comments.

2 Comments

nice solution - it runs with no error, but 1512231178 becomes 1512231227 it adds 49. mobile is varchar(30) NOT NULL
@Mucki, hmm, it is very strange, are you sure mobile us varchar? try SET mobile = '49' + cast(mobile as varchar(30))
1

Giorgi Nakeuri's clever problem substitution (prefixing for replacement) will work for your particular example. In other cases, where it is impossible to simplify the problem in such a way, you could use the INSERT string function, which does almost exactly what you want: replaces a substring of a specific length at a specific position with another substring. It does not allow you to also specify that the old substring match a specific value but you could use a WHERE clause for that, as Giorgi did:

UPDATE
  test
SET
  mobile = INSERT(mobile, 1, 1, '491')
WHERE
  mobile LIKE '1%'
;

If you needed to parametrise both the old and the new substring, this is how you could go about it:

UPDATE
  test
SET
  mobile = INSERT(mobile, 1, LENGTH(@OldValue), @NewValue)
WHERE
  mobile LIKE CONCAT(@OldValue, '%')
;

2 Comments

mysql> SET mobile = CONCAT('49', mobile) -> where mobile like '1%'; ERROR 1193 (HY000): Unknown system variable 'mobile'
SET mobile... isn't supposed to be a separate statement, it's part of the UPDATE actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.