Identity Column on VARCHAR

The primary key in a current table is set to VARCHAR(100). The columns start with S and then trail with several numbers. The new requirement is make all new records a number only and auto increment. However, I can't figure out how to make this auto increment with a data type of VARCHAR. Any thoughts?

SAMPLE TABLE:

CREATE TABLE Question (
        MyID      VARCHAR(100)      PRIMARY KEY      
      , MyCol      VARCHAR(30)            NOT NULL
)

SAMPLE OF EXISTING DATA:

MyID      MyCol
S00001      Example1
S00002      Example2
S00003      Example3
S00004      Example4
S00005      Example5

SAMPLE OF DESIRED DATA:

MyID      MyCol
S00005      Example5
S00004      Example4
S00003      Example3
S00002      Example2
S00001      Example1
5      Example10
4      Example9
3      Example8
2      Example7
1      Example6
LVL 3
computerstreberAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
in short: you cannot.
especially, you cannot mix identity values with non-identity values.

long answer:
you could create the functionality with a trigger...

or (better):

create 1 additional column that is identity (for all rows, hence).
create 1 additional computed column that will return the current value of MyID, if not null, otherwise the identity column value.

0
 
MohammedUCommented:
Keep in mind that you will end up with performance issue if the table has hight inserts....
Better to convert the col datatype if there are no non interger values ....
0
 
ErnariashCommented:
Here is the code for angelIII functionality to recreate the tables.
CREATE TABLE dbo.Question
	(
	MyID  AS  (CONVERT([varchar](100),ID,0)) PERSISTED NOT NULL,
	MyCol varchar(50) NULL,
	ID int NOT NULL IDENTITY (1, 1)
	)  ON [PRIMARY]
GO
 
 
 
ALTER TABLE dbo.Question ADD CONSTRAINT
	PK_Question PRIMARY KEY CLUSTERED 
	(
	MyID
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 
GO

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.