1

I have some characters that I want replace them with some other characters.

  • - => *
  • / => .
  • < => {
  • > => }

Also here is an example of a record in the table: (database)

+-------------------+
| - it <is> a test/ |
+-------------------+

And I want this output:

+-------------------+
| * it {is} a test. |
+-------------------+

Well, I can do that using 4 separated update queries: (through execute them one after the other)

UPDATE table SET `col` = REPLACE(`col`, '-', '*' );
UPDATE table SET `col` = REPLACE(`col`, '/', '.' );
UPDATE table SET `col` = REPLACE(`col`, '<', '{' );
UPDATE table SET `col` = REPLACE(`col`, '>', '}' );

Now I want to know, is there any shorter solution? (because in reality, there is more than 12 cases for replacing). For example, is it possible to I write all those symbol in an array and then put that array in the update query just for one time?

1 Answer 1

4
UPDATE table 
SET `col` = REPLACE(REPLACE(REPLACE(REPLACE(`col`, 
                                                         '>', 
                                                         '}' ), 
                                                 '<', 
                                                 '{' ), 
                                         '/', 
                                         '.' ), 
                                 '-', 
                                 '*' );

There is a function on postgresql translate to do exactly that. http://www.postgresql.org/docs/9.1/static/functions-string.html

Here I found a stored procedure replicating that function, (comment are in spanish).

http://www.forosdelweb.com/f86/funcion-translate-mysql-704190/

Sign up to request clarification or add additional context in comments.

2 Comments

Not to say that's not a good solution, but it should be noted that you're obviously sacrificing readability for efficiency with going this route.
Looks ugly, but can easily be generted in a programmatical way.

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.