- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Perform search/replace for only the first occurrence of a character with session variable in MySQL
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)
Advertisements