Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

database - how to prefix a string before sequence generated by postgresql?

This is a sequence

CREATE SEQUENCE technician_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;

It generates

1
2
3
4

I need the sequence as

AAA1
AAA2
AAA3
AAA4

Is it possible? I am very much new to postgresql.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here are a couple ways:

-- Referencing the sequence directly:
CREATE SEQUENCE test_seq;

SELECT 'AAAA'||nextval('test_seq')::TEXT;
 ?column? 
----------
 AAAA1

SELECT 'AAAA'||nextval('test_seq')::TEXT;
 ?column? 
----------
 AAAA2


-- Using a DEFAULT
CREATE TABLE abc 
    (val TEXT NOT NULL DEFAULT 'AAAA'||nextval('test_seq'::regclass)::TEXT, 
    foo TEXT);

INSERT INTO abc (foo) VALUES ('qewr');

SELECT * FROM abc;
  val  | foo  
-------+------
 AAAA3 | qewr

These assume that you have carefully decided how to proceed, based on the comments to your original question, as asked by the others.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...