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:
How can I do it using SQL query?
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;
来源:https://stackoverflow.com/questions/12152960/how-to-automatically-create-the-primary-key-that-has-the-following-series-a00100