คำอธิบาย
ใช้ REPLACE() ใน UPDATE SET เพื่อแทนที่สตริงเฉพาะส่วนในคอลัมน์
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
Code varchar(100) );
Query OK, 0 rows affected (0.50 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable values('8565-9848-7474');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('9994-6464-8737');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('6574-9090-7643');
Query OK, 1 row affected (0.17 sec)
แสดงข้อมูลก่อนอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+----------------+ | Code | +----------------+ | 8565-9848-7474 | | 9994-6464-8737 | | 6574-9090-7643 | +----------------+ 3 rows in set (0.00 sec)
คิวรี่ UPDATE REPLACE
mysql> update DemoTable set Code = replace(Code, '9994-6464-8737', '9994-9999-88888'); Query OK, 1 row affected (0.10 sec) Rows matched: 3 Changed: 1 Warnings: 0
ตรวจสอบข้อมูลหลังอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------------+ | Code | +-----------------+ | 8565-9848-7474 | | 9994-9999-88888 | | 6574-9090-7643 | +-----------------+ 3 rows in set (0.00 sec)
คำอธิบาย
- REPLACE(Code, 'old', 'new'): หา 'old' ใน Code แทนที่ด้วย 'new'
- แถวที่ 2: '9994-6464-8737' → '9994-9999-88888' (Changed: 1)
- แถวที่ 1, 3: ไม่มี '9994-6464-8737' → ไม่เปลี่ยน (Rows matched: 3 แต่ Changed: 1)
REPLACE ทั้งคอลัมน์ (ทุกครั้งที่เจอ)
UPDATE DemoTable SET Code = REPLACE(Code, '-', '/');
เปลี่ยน - ทั้งหมดเป็น / ในทุกแถว
CASE SENSITIVE
REPLACE() เป็น Case Sensitive ใช้ LOWER/UPPER หากต้องการ Case Insensitive:
UPDATE DemoTable SET Code = REPLACE(LOWER(Code), 'abc', 'xyz');