「已注销」 2015-12-08 09:37
浏览 66
已采纳

在PostgreSQL中生成顺序代码的最佳实践是什么?

Let's say I have to use formatted code for my transaction

for example: 20151208-1-20-xxx : Where xxx is in sequence number (eg: 001,002).

If I have to check the previous transaction code, it would be a problem if the transaction happens in the same time. What is the best practice to generate this kind of code?

Thank you~

  • 写回答

1条回答 默认 最新

  • dqlhsm9820 2015-12-08 10:07
    关注

    You can use a sequence. Create a function for convenience:

    create table test (code text);
    create sequence test_sequence;
    
    create function next_code()
    returns text language sql as $$
    select format('20151208-1-20-%s', to_char(nextval('test_sequence'), 'FM000'));
    $$;
    
    insert into test values (next_code());
    insert into test values (next_code());
    
    select * from test;
    
           code        
    -------------------
     20151208-1-20-001
     20151208-1-20-002
    (2 rows)
    

    Note that though it is probably the simplest effective and safe method, it does not provide gapless sequences.

    Read more: CREATE SEQUENCE and Sequence Manipulation Functions.

    Check a_horse_with_no_name's answer in ROLLBACK event triggers in postgresql for an alternative (gapless) solution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100