首页 文章

如何在postgresql中自动增加Alpha-Numeric值?

提问于
浏览
6

我正在使用 "PostgreSQL 9.3.5"

我有 TableStackOverflowTable )和 columns (SoId,SoName,SoDob) .

我希望列 SoIdSequence generator 是一个字母数字值 .

我想在postgresql中自动增加一个字母数字值 .

For eg : SO10001, SO10002, SO10003.....SO99999.

Edit:

如果明天我需要生成一个可以作为 SO1000E100, SO1000E101,... 且具有良好性能的序列 . 那么什么是最好的解决方案!

3 回答

  • 3

    使用id的序列和默认值:

    postgres=# CREATE SEQUENCE xxx;
    CREATE SEQUENCE
    postgres=# SELECT setval('xxx', 10000);
     setval 
    --------
      10000
    (1 row)
    
    postgres=# CREATE TABLE foo(id text PRIMARY KEY 
                                        CHECK (id ~ '^SO[0-9]+$' ) 
                                        DEFAULT 'SO'  || nextval('xxx'), 
                                b integer);
    CREATE TABLE
    postgres=# insert into foo(b) values(10);
    INSERT 0 1
    postgres=# insert into foo(b) values(20); 
    INSERT 0 1
    postgres=# SELECT * FROM foo;
       id    | b  
    ---------+----
     SO10001 | 10
     SO10002 | 20
    (2 rows)
    
  • 0

    您可以将列的默认值定义为 S 和正常 sequence 的串联,如下所示:

    CREATE SEQUENCE sequence_for_alpha_numeric
      INCREMENT 1
      MINVALUE 1
      MAXVALUE 9223372036854775807
      START 1
      CACHE 1;
    
    
    CREATE TABLE table1
    (
      alpha_num_auto_increment_col character varying NOT NULL,
      sample_data_col character varying,
      CONSTRAINT table1_pkey PRIMARY KEY (alpha_num_auto_increment_col)
    )
    ;
    
    ALTER TABLE table1 ALTER COLUMN alpha_num_auto_increment_col SET DEFAULT TO_CHAR(nextval('sequence_for_alpha_numeric'::regclass),'"S"fm000000');
    

    Test:

    ^
    insert into table1 (sample_data_col) values ('test1');
    insert into table1 (sample_data_col) values ('test2');
    insert into table1 (sample_data_col) values ('test3');
    
    select * from table1;
     alpha_num_auto_increment_col | sample_data_col
    ------------------------------+-----------------
     S000001                      | test1
     S000002                      | test2
     S000003                      | test3
    (3 lignes)
    

    如何使用sequences

    如何使用to_char功能 .

  • 2

    创建如下序列

    CREATE SEQUENCE seq_autoid
      INCREMENT 1
      MINVALUE 1
      MAXVALUE 9223372036854775807
      START 10000
    

    创建一个函数来生成字母数字id

    create or replace function auto_id () returns varchar as $$
    select 'SO'||nextval('seq_autoid')
    $$ language sql
    

    并尝试此示例表

    create table AAA(id text ,namez text)
    
    insert into AAA values (auto_id(),'MyName')
    insert into AAA values (auto_id(),'MyName1')
    insert into AAA values (auto_id(),'MyName2')
    

相关问题