A. Gisbert
A. Gisbert

Reputation: 163

SQL Server-How can I make a varchar auto increment

I am trying to run the following script but it is failing and I do not know why:

DROP TABLE table;
CREATE SEQUENCE seq START WITH 0;
CREATE TABLE table (
    id VARCHAR(512) PRIMARY KEY AS ('0000000000' + CAST(NEXT VALUE FOR seq AS VARCHAR(512)), 10),
    field VARCHAR(512),
    field VARCHAR(512)
);

I want to cast the number to string in order to match the requirements of other part of the code

Upvotes: 2

Views: 1673

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

How about a different approach? Just use an identity column for the table. Then add a generated column that provides your string representation:

CREATE TABLE t (
    t_id int identity(1, 1) primary key,
    t_id_str as (right('0000000000' + CAST(t_id AS VARCHAR(512)), 10))
);

Upvotes: 4

Related Questions