Home  >  Article  >  Database  >  Perform a search/replace on only the first occurrence of a session variable in MySQL

Perform a search/replace on only the first occurrence of a session variable in MySQL

王林
王林forward
2023-09-25 12:01:021243browse

仅对 MySQL 中会话变量第一次出现的字符执行搜索/替换

To perform a search/replace on only the first occurrence, use the CONCAT and REPLACE() functions.

Query as follows to set user-defined session variables -

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

Here, k will be replaced by i only once. The query is as follows. We also used INSTR() -

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 showing only the first occurrence of the character being replaced -

+------------------------+------------------------+
| NewString              | ChangeOnlyOneTime      |
+------------------------+------------------------+
| Thks ks is a my string | This ks is a my string |
+------------------------+------------------------+
1 row in set (0.00 sec)

The above is the detailed content of Perform a search/replace on only the first occurrence of a session variable in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete