oracle(plsql)生成流水号
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;
v_sql := ‘SELECT TO_CHAR(SYSDATE,”YYYYMMDD”) FROM DUAL’;
EXECUTE IMMEDIATE v_sql INTO v_date_no;
v_old_num := to_number(substr(v_old_no, 12, 3));
v_new_num := lpad(to_char(v_old_num+1), 3, ‘0’);
IF v_old_no IS NULL OR substr(v_old_no, 3, 8) <> v_date_no THEN
v_new_no := v_prefix || v_date_no || ‘-‘ || ‘001’;
ELSE
v_new_no := v_prefix || v_date_no || ‘-‘ || v_new_num;
END IF;
RETURN v_new_no;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
END fn_no_make;