การใช้ REPLACE() ลบอักขระเฉพาะ
ฟังก์ชัน REPLACE(str, from_str, to_str) แทนที่ from_str ด้วย to_str ใช้ REPLACE(col, '%', '') ลบ %
ตัวอย่าง
mysql> create table DemoTable828(
CustomerName varchar(100),
InterestRate varchar(100) );
Query OK, 0 rows affected (0.50 sec)
mysql> insert into DemoTable828 values('Chris','10%');
mysql> insert into DemoTable828 values('Robert','11.5%');
mysql> insert into DemoTable828 values('David','15.90%');
mysql> insert into DemoTable828 values('Bob','20%');
คำสั่ง UPDATE ลบ %
mysql> update DemoTable828 set InterestRate = replace(InterestRate, '%', '');
Query OK, 4 rows affected (0.18 sec)
ผลลัพธ์
+--------------+--------------+
| CustomerName | InterestRate |
+--------------+--------------+
| Chris | 10 |
| Robert | 11.5 |
| David | 15.90 |
| Bob | 20 |
+--------------+--------------+
การใช้ใน SELECT (ไม่แก้ไขข้อมูล)
SELECT CustomerName, REPLACE(InterestRate, '%', '') as Rate FROM DemoTable828;
การแปลงเป็นตัวเลขจริง
-- แปลงเป็น DECIMAL สำหรับคำนวณ
SELECT CAST(REPLACE(InterestRate, '%', '') AS DECIMAL(10,2)) as Rate FROM DemoTable828;
สรุป
ใช้ REPLACE(column, '%', '') ลบเครื่องหมาย % ออกจากสตริง แล้ว CAST(... AS DECIMAL) ถ้าต้องคำนวณต่อ