How to automatically create the primary key that h

2019-04-14 12:29发布

I want to create a primary key(auto-increment) which is start with A001000001. Here A001 would be constant and 000001 would be iterate.

I want rows like this:

enter image description here

How can I do it using SQL query?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-14 13:06

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;

查看更多
贪生不怕死
3楼-- · 2019-04-14 13:14

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)
查看更多
贪生不怕死
4楼-- · 2019-04-14 13:17

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

查看更多
登录 后发表回答