Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
adam0101 Avatar asked Mar 06 '17 22:03

adam0101


People also ask

How do I create a column sequence number in SQL?

The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.

How do I concatenate values in the same column?

Notice that the plus symbol ('+') is used to perform the concatenation. You can bypass this error by mapping the values to strings using the following syntax: df['New Column Name'] = df['1st Column Name'].

How do I concatenate values in PostgreSQL?

In PostgreSQL, the CONCAT function is used to concatenate two or more strings into one. Let's analyze the above syntax: The CONCAT function accepts a list of string convertible arguments. A string in this context means any of the following data types: char, varchar, or text.


1 Answers

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
like image 120
Zohar Peled Avatar answered Oct 08 '22 19:10

Zohar Peled