[SQL] 產生唯一的交易編號 – Generating unique transaction IDs

Intro

在交易的應用場景下,可能需求為透過資料庫符合 ACID 快速產生唯一的交易編號作為 Primary key 或是 Unique key。


MySQL 實作

假設定義一組16碼的交易編號,格式為YYYYMMDD(8) + 流水號(8)。
這前提下代表一天內不建立超過8位數的 record,就可以利用 MySQL auto_increment 搭配 last_insert_id() 來實現:

START TRANSACTION;

INSERT INTO transactions (transaction_date, amount) VALUES (NOW(), 100);

SET @last_id = LAST_INSERT_ID();
SET @fixed_length = 8;
SET @last_digits = LPAD(SUBSTRING(CAST(@last_id AS CHAR), -LEAST(@fixed_length, LENGTH(CAST(@last_id AS CHAR)))), @fixed_length, '0');
SET @transaction_id = CONCAT(DATE_FORMAT(NOW(), '%Y%m%d'), @last_digits);

SET @transaction_id = CONCAT('TRX-', @transaction_id);

UPDATE transactions SET transaction_id = @transaction_id WHERE id = @last_id;

COMMIT;

當然,整個 SQL TRANSACTION 也可以選擇抽離給 Backend Server 去做,SQL server 即可省掉 Function process。

Leave a Reply

Your email address will not be published. Required fields are marked *