Thay thế ký tự trong cột với hàm REPLACE() MySQL
Hàm REPLACE(cot, 'chuoi_cu', 'chuoi_moi') thay thế tất cả lần xuất hiện của chuỗi con.
Tạo bảng và dữ liệu
mysql> create table DemoTable ( Name varchar(20) ); Query OK, 0 rows affected (0.69 sec)
mysql> insert into DemoTable values('John Smitk');
mysql> insert into DemoTable values('David Miller');
mysql> insert into DemoTable values('Adam Smitk');
Dữ liệu ban đầu
+--------------+ | Name | +--------------+ | John Smitk | | David Miller | | Adam Smitk | +--------------+
Cập nhật: Thay 'k' thành 'h' (sửa chính tả Smith)
mysql> update DemoTable set Name=replace(Name,'k','h'); Query OK, 2 rows affected (0.13 sec) Rows matched: 3 Changed: 2 Warnings: 0
Kết quả
+--------------+ | Name | +--------------+ | John Smith | | David Miller | | Adam Smith | +--------------+
Đặc điểm REPLACE():
- Thay thế TẤT CẢ lần xuất hiện:
REPLACE('aaa', 'a', 'b')→ 'bbb' - Phân biệt chữ hoa/thường (case-sensitive)
- Trả về chuỗi mới, không sửa trực tiếp cột nếu dùng trong SELECT
- Cập nhật thực tế cần
UPDATE ... SET cot = REPLACE(cot, ...)
Ví dụ khác: Xóa khoảng trắng: REPLACE(cot, ' ', ''), chuẩn hóa số điện thoại: REPLACE(REPLACE(REPLACE(phone, '-', ''), '(', ''), ')', '').