Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a MySQL equivalent for Translate() in Oracle

I am retrieving some password values from MySQL table in Hibernate and replace that with other strings in MySQL. I understand that there is translate() in Oracle to do the replacement but I haven't found any of the same in MySQL. Would there be any alternate solution other than Replace() in MySQL or any libraries that can be used for the same?

like image 940
John Avatar asked Jun 26 '15 06:06

John


People also ask

What is TRANSLATE in Oracle SQL?

TRANSLATE lets you make several single-character, one-to-one substitutions in one operation. This function does not support CLOB data directly. However, CLOB s can be passed in as arguments through implicit data conversion.

What is the difference between Replace and TRANSLATE functions in Oracle?

REPLACE() replaces one string with another string. Therefore, if a string contains multiple characters, each character must be in the same order. TRANSLATE() on the other hand, replaces each character one by one, regardless of the order of those characters.

How do you TRANSLATE data in SQL?

SQL Server TRANSLATE() Function The TRANSLATE() function returns the string from the first argument after the characters specified in the second argument are translated into the characters specified in the third argument.

What translator does SQL use?

The BigQuery interactive SQL translator can translate the following SQL dialects into Google Standard SQL: Amazon Redshift SQL.


2 Answers

Till now there is no equivalent of Oracle's TRANSLATE() function in MySQL. However, you can achieve the desired results by using nested REPLACE() functions.

Adding an example -
Oracle query -
SELECT TRANSLATE('Vikas#Bharti-Infy', '#-', '_.') FROM dual;

Vikas_Bharti.Infy

The equivalent MySQL query will be -
SELECT REPLACE(REPLACE('Vikas#Bharti-Infy', '#', '_'),'-','.');

Vikas_Bharti.Infy

like image 129
Vikas Bharti Avatar answered Oct 14 '22 10:10

Vikas Bharti


You could create one like this:

CREATE FUNCTION `translate`(subject varchar(255), what varchar(255), replace_to varchar(255)) RETURNS varchar(255)
begin
 declare c int unsigned default 0;
 declare result varchar(255);

 set result = subject;

 while c <= length(subject) do
  set result = replace(result, mid(what, c, 1), mid(replace_to, c, 1) );
  set c=c+1;   
 end while;

 return result; 
end

Then use:

mysql> select translate('(123) 1234-1234', '( )-','.,.,');
+---------------------------------------------+
| translate('(123) 1234-1234', '( )-','.,.,') |
+---------------------------------------------+
| .123.,1234,1234                             |
+---------------------------------------------+
1 row in set (0.00 sec)
like image 5
Flavio Maia Avatar answered Oct 14 '22 10:10

Flavio Maia