How to create a scan sequence in the Postgres database?

Asked

Viewed 266 times

6

I have the following table in the database Postgres:

CREATE TABLE customer
(
  userid character varying(30) NOT NULL,
  firstname character varying(30) NOT NULL,
  lastname character varying(30) NOT NULL,
  balance double precision NOT NULL,
  PRIMARY KEY (userid)
)  

It would be possible to create a sequence of the auto increment type but one of the type VARCHAR?

'Cause I got an object of business rule that needs a guy String.

I know the procedure for creating a sequence with the type serial:

CREATE TABLE customer
(
  userid serial NOT NULL,
  ...
  ...
  ...
  PRIMARY KEY (userid)
)    

But like I said before, I need a guy VARCHAR, because the values that will be entered as the primary key will have this form:

id001  
id002  
id003  

1 answer

5

With varchar you will have to create a tigger and increase its field.

Example:

CREATE FUNCTION update_transaction_id() RETURNS trigger AS $BODY$
BEGIN
  NEW.userid  :=  'id' || nextval('seq_name');
  RETURN NEW;
END; 
$BODY$ LANGUAGE 'plpgsql';

Whereas seq_name is the name of your Generator. (If it does not exist you must create it)

Create Generator: CREATE SEQUENCE seq_name START 1;

And the Trigger on the table to run Function:

CREATE TRIGGER inc_id
  AFTER INSERT
  ON customer
  FOR EACH ROW
  EXECUTE PROCEDURE update_transaction_id();
  • @That I know!! But I want to create a varchar type value that is high increment!!

  • 1

    Wait I will change my answer with an example.

  • @Eduardobrito I still thought about using a procedure to do this but I dismissed the idea, however, with a Tigger , as I could do this?

  • I changed the answer, take a look if it can help you.

  • 1

    If you solve your problem and want to of course give me the best answer I thank you.

  • @Eduardobrito This Generator seq_name I must create in what way?

  • CREATE SEQUENCE seq_name START 1;

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.