开发者

auto increment custom ID in database table

开发者 https://www.devze.com 2023-02-06 21:29 出处:网络
I have a EMPLOYEE table开发者_JAVA百科 with EMP_ID,EMP_NAME,EMP_ADDRESS.EMP_ID should have the following format.

I have a EMPLOYEE table开发者_JAVA百科 with EMP_ID,EMP_NAME,EMP_ADDRESS. EMP_ID should have the following format.

EMP001
EMP002
EMP003
......

I also need to use EMP_ID as the primary key and should be auto generated is it possible?


Use an IDENTITY and a computed column?

CREATE TABLE EMPLOYEE (
     RealID int NOT NULL IDENTITY (1, 1),
     EMP_NAME ...
     ...
     /*gives 000-999. Change the RIGHT as needed to give more*/
     EMP_ID AS 'EMP' + RIGHT('000000000' + CAST(RealID as varchar(10)), 3)

     CONSTRAINT PK_EMPLOYEE PRIMARY KEY CLUSTERED (EMP_ID)
     )

You can change the RIGHT to cover as many digits as needed, or you may not want leading zeroes:

     EMP_ID AS 'EMP' + CAST(RealID as varchar(10))
0

精彩评论

暂无评论...
验证码 换一张
取 消