Perform search/replace for only the first occurrence of a character with session variable in MySQL

MySQLMySQLi Database

To perform search/ replace for only the first occurrence, use the CONCAT and REPLACE() function.

The query is as follows to set user defined session variable −

mysql> set @Sentence='Thks ks is a my string';
Query OK, 0 rows affected (0.00 sec)

In this k will be replaced with i only once. The query is as follows. We have used INSTR() also −

mysql> select @Sentence as NewString ,CONCAT(REPLACE(LEFT(@Sentence,
INSTR(@Sentence, 'k')), 'k', 'i'),
   -> SUBSTRING(@Sentence, INSTR(@Sentence, 'k') + 1)) as ChangeOnlyOneTime;

The following is the output displaying only the first occurrence of a character is replaced −

+------------------------+------------------------+
| NewString              | ChangeOnlyOneTime      |
+------------------------+------------------------+
| Thks ks is a my string | This ks is a my string |
+------------------------+------------------------+
1 row in set (0.00 sec)
raja
Published on 27-Feb-2019 10:19:15
Advertisements