ใช้ Attribute ZEROFILL ร่วมกับชนิดข้อมูลตัวเลข (INT, BIGINT, DECIMAL) เพื่อแสดงเลข 0 นำหน้าอัตโนมัติจนครบความยาวที่กำหนด
Syntax
CREATE TABLE table_name (
column_name INT(display_width) ZEROFILL
);
display_width- จำนวนหลักที่ต้องการ (เช่น INT(4) = 4 หลัก)ZEROFILL- เติม 0 ด้านหน้าอัตโนมัติ- จะเพิ่ม
UNSIGNEDอัตโนมัติ (ค่าไม่ติดลบ)
ตัวอย่างการใช้งาน
1. สร้างตารางพร้อม ZEROFILL
mysql> create table DemoTable1913 (
-> Code int(4) ZEROFILL AUTO_INCREMENT NOT NULL,
-> PRIMARY KEY(Code)
-> ); Query OK, 0 rows affected (0.00 sec)
2. เพิ่มข้อมูล (ให้ AUTO_INCREMENT ทำงาน)
mysql> insert into DemoTable1913 values(1); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1913 values(2); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1913 values(3); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1913 values(4); Query OK, 1 row affected (0.00 sec)
3. แสดงผล (Zero-padded อัตโนมัติ)
mysql> select * from DemoTable1913;
+------+ | Code | +------+ | 0001 | | 0002 | | 0003 | | 0004 | +------+ 4 rows in set (0.00 sec)
รายละเอียด ZEROFILL
| ค่าที่ Insert | INT(4) ZEROFILL | INT(6) ZEROFILL |
|---|---|---|
| 1 | 0001 | 000001 |
| 42 | 0042 | 000042 |
| 1234 | 1234 | 001234 |
| 12345 | 12345 (เกิน 4 หลัก) | 012345 |