Postgre数据库生成自定义订单号

复制代码 代码如下:CREATE OR REPLACE
FUNCTION fn_no_make(v_prefix VARCHAR2, v_table_name VARCHAR2,
v_number_col VARCHAR2)/* * v_prefix: 编码前缀两位 *
v_table_name:编码所在表名 * v_number_col:编码所在列名 */ RETURN
VARCHAR2 IS v_old_no VARCHAR2(50); –原编码 v_new_no VARCHAR2(50);
–新编码 v_old_num NUMBER; –原编码后三位编号 v_new_num
VARCHAR2(10); –新编码后三位编号 v_date_no VARCHAR2(10);
–当前日期编号 v_sql VARCHAR2(4000);BEGIN v_sql := ‘SELECT MAX(‘ ||
v_number_col || ‘) FROM ‘ || v_table_name; EXECUTE IMMEDIATE v_sql
INTO v_old_no;

使用postgre的存储过程生成自定义订单号
CREATE OR REPLACE FUNCTION get_order_no(tname VARCHAR,cname
VARCHAR,cprefix VARCHAR)

v_sql := ‘SELECT TO_CHAR(SYSDATE,”YYYYMMDD”) FROM DUAL’; EXECUTE
IMMEDIATE v_sql INTO v_date_no;

RETURNS VARCHAR
AS
$$
DECLARE
–当前的订单号
now_order_no VARCHAR;
  –存储当前日期
now_day VARCHAR;
–新的订单号
new_order_no VARCHAR;
–旧的时间
old_date VARCHAR;
–旧的订单编号
old_order_no BIGINT;
–新的订单编号
order_no VARCHAR;
BEGIN
  EXECUTE ‘SELECT MAX (‘||cname||’) FROM ‘||tname||’ WHERE booking_time
> CURRENT_DATE’ INTO now_order_no;
   –通过截取 获得订单号中的日期
  old_date = substr(now_order_no,1,8);
  –通过截取获得旧的订单编号
  old_order_no = substr(now_order_no,10,5);
   –当前日期
  now_day = to_char(CURRENT_DATE,’yyyyMMdd’);
  –如果没有获得大于当前日期的订单 则从新插入
  IF now_order_no is NULL THEN
  new_order_no = cprefix || now_day || ‘00001’;
  RETURN new_order_no;
   –如果 查询的时间 等于当前时间
  ELSEIF old_date != now_day THEN
  new_order_no = cprefix || now_day || ‘00001’;
RETURN new_order_no;
  ELSE
  order_no= cast(old_order_no+1 as varchar);
  order_no = LPAD(order_no,5,’0′);
  new_order_no = cprefix || now_day || order_no;
RETURN new_order_no;
  END IF;

v_old_num := to_number(substr(v_old_no, 12, 3)); v_new_num :=
lpad(to_char(v_old_num+1), 3, ‘0’);

END;
$$
LANGUAGE ‘plpgsql’ VOLATILE;