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?
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.
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.
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.
The BigQuery interactive SQL translator can translate the following SQL dialects into Google Standard SQL: Amazon Redshift SQL.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With