基准要求是以以下格式创建订单号:
(M)M-SSS
其中MM代表当前月份,SSSS代表该月份的订单序列。例如,1-002将代表1月份提交的第二个订单。
使用TRIGGER我希望自动增量和插入能够透明地工作。
不幸的是,自从我触及存储过程以来已经很长时间了,这是我第一次涉足postgresql。任何指向正确方向的帮助都将非常感激。
更新:这是使用@ peterm代码的最终实现
-- The trigger
CREATE TRIGGER add_order_number
BEFORE INSERT ON orders FOR EACH ROW
EXECUTE PROCEDURE order_number_update();
-- The trigger function
CREATE FUNCTION order_number_update() RETURNS TRIGGER AS $$
DECLARE
next_order TEXT;
BEGIN
-- get the next order number
SELECT INTO next_order CONCAT(CAST(DATE_PART('MONTH', CURRENT_DATE) AS VARCHAR(2)),
'-',
LPAD(CAST(COALESCE(CAST(RIGHT(MAX(order_number), 3) AS INT), 0) + 1 AS VARCHAR(3)), 3, '0'))
FROM orders
WHERE CAST(LEFT(order_number, STRPOS(order_number, '-') - 1) AS INT) = DATE_PART('MONTH', CURRENT_DATE);
-- update the field
NEW.order_number = next_order;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
注意:通过将更新添加为BEFORE INSERT触发器,它以完全透明且可预测的方式运行,就像普通的SERIAL或BIGSERIAL字段一样。
答案 0 :(得分:2)
你在找这样的东西吗?
-- Next No calculated for current month
SELECT CONCAT(CAST(DATE_PART('MONTH', CURRENT_DATE) AS VARCHAR(2)),
'-',
LPAD(CAST(COALESCE(CAST(RIGHT(MAX(order_no), 4) AS INT), 0) + 1 AS VARCHAR(4)), 4, '0')) next_no
FROM orders
WHERE CAST(LEFT(order_no, STRPOS(order_no, '-') - 1) AS INT) = DATE_PART('MONTH', CURRENT_DATE)
;
输出:
| NEXT_NO |
-----------
| 5-0001 |
假设有order_no
='1-0001'的记录,那么
-- Next No for January
SELECT CONCAT(CAST(DATE_PART('MONTH', DATE '2013-01-01') AS VARCHAR(2)),
'-',
LPAD(CAST(COALESCE(CAST(RIGHT(MAX(order_no), 4) AS INT), 0) + 1 AS VARCHAR(4)), 4, '0')) next_no
FROM orders
WHERE CAST(LEFT(order_no, STRPOS(order_no, '-') - 1) AS INT) = DATE_PART('MONTH', DATE '2013-01-01')
;
输出:
| NEXT_NO |
-----------
| 1-0002 |
<强> SQLFiddle 强>