adam0101
adam0101

Reputation: 31075

Is it possible to concatenate a string to a sequence value and use as a column default value?

I'd like to set a default value for a column from a sequence like what is done here, but also prepend a value in front of the sequence so the value saved in the table looks like P123. Is that possible?

Upvotes: 7

Views: 3481

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82524

It's totally possible.
Changing the example from the post you've linked to something like this:

create sequence mainseq as bigint start with 1 increment by 1;

create table mytable (
    id      varchar(20) not null constraint DF_mytblid default 'p' + CAST(next value for mainseq as varchar(10)),
    code    varchar(20) not null
)

Test:

INSERT INTO MyTable (Code) VALUES ('asdf'), ('cvnb')

SELECT *
FROM MyTable

Results:

id  code
p1  asdf
p2  cvnb

Upvotes: 5

Related Questions