Custom auto-increment field in postgresql (Invoice/Order No.)

不羁岁月 提交于 2019-12-20 03:35:12

问题


The baseline requirement is to create an order number in the format:

(M)M-SSS

Where MM represents the current month and SSSS represents the order sequence for that month. For example 1-002 would represent the second order submitted in January.

Using a TRIGGER I'd like the auto-increment and insert to work transparently.

Unfortunately, it has been a long time since I have touched a stored procedure and this is my first foray into postgresql. Any help pointing in the right direction would be greatly appreciated.

Update: Here's the final implementation using @peterm's code

-- 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;

Note: By adding the update as an BEFORE INSERT trigger it functions in a completely transparent and predictable manner, much like a normal SERIAL or BIGSERIAL field would.


回答1:


Are you looking for something like this?

-- 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)
;

Output:

| NEXT_NO |
-----------
|  5-0001 |

Assuming that there is a record with order_no = '1-0001' then

-- 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')
;

Output:

| NEXT_NO |
-----------
|  1-0002 |

SQLFiddle



来源:https://stackoverflow.com/questions/16598959/custom-auto-increment-field-in-postgresql-invoice-order-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!