How to automatically create the primary key that has the following series A001000001 … A001xxxxxx in SQL?

非 Y 不嫁゛ 提交于 2019-12-04 17:48:50

For SQL Server (you didn't clearly specify which RDBMS you're using), my suggestion would be:

  • add a INT IDENTITY column to your table - and quite frankly, I would make that column the primary key
  • add a computed column to your table that does this "prefixing"

Something like:

CREATE TABLE dbo.YourTable
( ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED
)

That way, if you insert a row, the ID gets set automatically, and the EmpID will also be set automatically to values like A0010000001, A0010000002, .... and so forth.

If you want to put the primary key on the EmpID column, then you need to make sure to include the NOT NULL specification when creating it:

CREATE TABLE dbo.YourTable
( ID INT IDENTITY(1,1),
  EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED NOT NULL
)

and then you can put the primary key constraint on that column:

ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (EmpID)

You can create BEFORE INSERT trigger, check MAX id value, increment it, add prefix, and then insert.

its much easier than you think ;)

CREATE TABLE bob ( id MEDIUMINT NOT NULL AUTO_INCREMENT, foo CHAR(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!