创建一个序列,其值是字符和数字的混合 [英] Creating a sequence which values are a mix of character and numbers
本文介绍了创建一个序列,其值是字符和数字的混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Postgres 9.1,并想创建一个可用作主键的序列,该序列应如下所示:
I am using Postgres 9.1 and would like to create a sequence which I can use as primary key and which should look like this:
| entity_id_seq |
-----------------
| X0001 |
| X0002 |
....
| X0123 |
和 nextval('entity_id_seq')
返回'X0124'
。
任何想法以及使用纯Postgres怎么可能?
Any idea's how and if this is possible with pure Postgres?
非常感谢!
推荐答案
像这样的东西应该没问题:
Something like this should be fine:
创建序列:
CREATE SEQUENCE special_seq;
是否创建函数:
CREATE OR REPLACE FUNCTION
nextval_special()
RETURNS TEXT
LANGUAGE sql
AS
$$
SELECT 'X'||to_char(nextval('special_seq'), 'FM0000');
$$;
现在检查是否有效:
SELECT nextval_special() FROM generate_series(1,10);
nextval_special
-----------------
X0001
X0002
X0003
X0004
X0005
X0006
X0007
X0008
X0009
X0010
(10 rows)
现在您可以使用上述函数创建表:
Now you can create the table using the above function:
CREATE TABLE test (
id TEXT PRIMARY KEY DEFAULT nextval_special(),
a int
);
,或者不带函数,只需通过以下函数进行简单查询:
or just without function with the simple query from the function:
CREATE TABLE test (
id TEXT PRIMARY KEY DEFAULT 'X'||to_char(nextval('special_seq'), 'FM0000'),
a int
);
这篇关于创建一个序列,其值是字符和数字的混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文